spring.xml中配置了文件后, 通过下行代码 BraveKnight实例的时候报错com.sun.proxy.$Proxy6 cannot be cast to model.BraveKnight
BraveKnight braveKnight = (BraveKnight) context.getBean("knight");
spring.xml配置如下:
<aop:config >
<!--Spring aop配置命名空间,将Minstrel bean声明为一个切面-->
<aop:aspect ref="minstrel">
<!--定义切点 execution属性选择所应用的通知。表达式使用AspectJ切点表达式语言-->
<aop:pointcut id="embark" expression="execution(* *.embarkOnQuest(..))"/>
<!--声明前置通知-->
<aop:before pointcut-ref="embark" method="singBeforeQuest"/>
<!--声明后置通知-->
<aop:after pointcut-ref="embark" method="singAfterQuest"/>
</aop:aspect>
</aop:config>
造成原因:
Spring AOP实现方式有两种,一种使用JDK动态代理,另一种通过CGLIB来为目标对象创建代理。如果被代理的目标实现了至少一个接口,则会使用JDK动态代理,所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理,创建的代理类是目标类的子类。
解决方法:
在 aop-config配置添加上: proxy-target-class="true"。如下:
<aop:config proxy-target-class="true">
原理:proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理