在使用Spring AOP時,遇到以下的錯誤:java
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)spring
看報錯信息,顯示的是動態代理生成的類沒法轉換到咱們自定義的實現類。app
在aop:config標籤中添加 proxy-target-class="true" 便可。spa
【解釋說明】.net
按照博客的說法:http://blog.csdn.net/z69183787/article/details/17161297代理
因爲生成代理類有兩種方式:JDK和CGLIB,一種是基於接口的,一種是基於類的。code
若是添加上面的屬性則使用基於類的cglib的方式,相反,若是沒有寫或者是false則經過jdk的基於接口的方式生成代理類。orm
固然,若是自己不是基於接口的,那麼會自動使用cglib的方式,在這裏很奇怪爲何沒有自動走cglib的方式。blog
箇中原因,還得去看aop的源碼,這裏先作下記錄。接口
<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>