AOP can be used in spring to weave aspects. This is commonly used for database transactions using the @Transactional annotation. However, this means that spring has to make proxy objects for beans which use these annotations. This can lead to the error,
Error Cannot convert value of type [$Proxy...] to required type
Basically what is happening is that spring is creating the proxy objects from the corresponding interfaces but in the spring context an actual implementation of the interface is required as a property by a bean. In this case spring can't guarantee that the proxy implementation will satisfy the beans requirement and this error is thrown.
Solution 1
The first and best solution is to correct the receiving bean to take an interface instead of an implementation. Most beans should take interfaces so that the implementation can easily be swapped in the spring configuration. Once the beans are wired purely with interfaces this problem with go away.
Solution 2
Where solution 1 above isn't an option it is possible to tell spring to proxy classes and not interfaces. This is done with this spring command
<aop:config proxy-target-class="true"/>
This requires the correct namespace definitions at the top of the spring context xml file such as
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
No comments:
Post a Comment