AOP: the proxy-target-class of config causes classcastexception.
First look at a piece of code:
1 package com. test;
2 public interface movein {
3
4}
1 package com. test;
2 @ Service (value = "movemanager ")
3 @ transactional
4 public class movemanager implements movein {
5
6}
In moveaction, we use two methods to get the movemanager object:
First: Automatic injection with @ autowired Annotation
@ Autowired
Private movemanager;
Type 2: Use getbean () in applicationcontext ()
Applicationcontext CTX = *************
Movemanager movem = (movemanager) CTX. getbean ("movemanager ");
The first method is used. When an action is called, a similar exception is thrown: beancreationexception: cocould not autowire field: private com. Test. movemanager com. Test. moveaction. movemanager.
The second method is used when movemanager movem = (movemanager) CTX is executed. getbean ("movemanager"); will throw a similar exception: Java. lang. classcastexception: $ proxy40 cannot be cast to com. test. movemanager. Change the code to movein movem = (movein) CTX. getbean ("movemanager"); and then run normally, but this is not the result I want, and I do not want to change the forced conversion type.
Now let's talk about why this problem occurs and how to solve it. In Spring AOP, JDK dynamic proxy or cglib is used to create a proxy for the target object. By default, if the target object of the proxy implements at least one interface, JDK dynamic proxy is used. All interfaces implemented by this object type will be proxies. If the target object does not implement any interfaces, A cglib proxy is created. This explains why the classcastexception exception occurs when the forced type is movemanager and the forced type is movein, because movemanager is represented by JDK. If you want to proxy all methods of the target object without changing the code, instead of implementing the self-interface method (Force cglib proxy), you only need to <AOP: config> proxy-
Set the target-class attribute to true:
<AOP: config proxy-target-class = "true"/>
Or change movein to abstract class.
<AOP: configProxy-target-class = "true">
<AOP: pointcut id = "insertnewsmethod" expression = "execution (* COM. yssoft. News. Service. *. * (..)"/>
<AOP: Advisor advice-ref = "txadvice" pointcut-ref = "insertnewsmethod"/>
</AOP: config>
The default value of proxy-target-class is false.
Java. Lang. classcastexception: $ proxy0 exception
Set it to true.