学习Spring AOP JDK代理与CGLIB代理的错误记录
Spring的JDK代理和CGLib代理的区别在于,JDK只能代理实现了接口的类,如果类没有实现接口,则必须使用CGLIB。
Spring默认使用的是JDK代理,正常来说他会自动改变使用的代理。但有时会出现问题
<bean id="chinese" class="com.thunder.practice.test1.Chinese"></bean> <bean id="english" class="com.thunder.practice.test1.English"></bean> <bean id="aopMethod" class="com.thunder.practice.test1.AopMethod"/> <aop:config> <aop:aspect ref="aopMethod"> <aop:pointcut expression="execution(* com.thunder.practice.test1.Person.say(..))" id="say"/> <aop:before method="before" pointcut-ref="say"/> <aop:after method="after" pointcut-ref="say"/> </aop:aspect> </aop:config>
在类中:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class AopTest { @Resource public Person chinese; @Resource public English english; @Test public void test(){ chinese.say(); } @Test public void test2(){ english.say(); } }
此时会报错: Bean named 'english' must be of type [com.thunder.practice.test1.English], but was actually of type [com.sun.proxy.$Proxy11]
需要强制使用CGLIB代理:
<aop:config proxy-target-class="true"> <!-- 在config中指定proxy-target-class="true"即可 -->

浙公网安备 33010602011771号