在使用Spring AOP時,遇到如下的錯誤:
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to com.spring.test.setter.Instrumentalist
at com.spring.test.setter.test.main(test.java:12)
看報錯信息,顯示的是動態代理生成的類無法轉換到我們自定義的實現類。
解決辦法:
在aop:config標簽中添加 proxy-target-class="true" 即可。
【解釋說明】
按照博客的說法:http://blog.csdn.net/z69183787/article/details/17161297
由於生成代理類有兩種方式:JDK和CGLIB,一種是基於接口的,一種是基於類的。
如果添加上面的屬性則使用基於類的cglib的方式,相反,如果沒有寫或者是false則通過jdk的基於接口的方式生成代理類。
當然,如果本身不是基於接口的,那么會自動使用cglib的方式,在這里很奇怪為什么沒有自動走cglib的方式。
個中緣由,還得去看aop的源碼,這里先做下記錄。
下面是我自己的spring配置文件,僅供參考
<aop:config proxy-target-class="true"> <aop:aspect ref="audience"> <aop:before pointcut="execution(* com.spring.test.action1.Performer.perform(..))" method="takeSeats"/> <aop:before pointcut="execution(* com.spring.test.action1.Performer.perform(..))" method="turnOffCellPhones"/> <aop:after-returning pointcut="execution(* com.spring.test.action1.Performer.perform(..))" method="applaud"/> <aop:after-throwing pointcut="execution(* com.spring.test.action1.Performer.perform(..))" method="demandRefund"/> </aop:aspect> </aop:config>