項目中使用AOP出現的一個錯誤:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'com.pajk.apate.controller.DoctorControllerTest':
Unsatisfied dependency expressed through field 'doctorController';
nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException:
Bean named 'doctorController' is expected to be of type 'com.demo.controller.DoctorController'
but was actually of type 'com.sun.proxy.$Proxy110'
出現這個問題的原因是:
Spring AOP 默認使用JDK動態代理。如果業務對象未實現接口,則默認使用CGLIB代理。
If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. All of the interfaces implemented by the target type will be proxied. If the target object does not implement any interfaces then a CGLIB proxy will be created.
如果要代理的目標對象實現至少一個接口,則將使用JDK動態代理。 目標類型實現的所有接口都將被代理。 如果目標對象未實現任何接口,則將創建CGLIB代理。
以上是Spring AOP官方文檔:(更多官方文檔參考我的另外一篇博客:面向切面的Spring編程(官方文檔翻譯))
因爲DoctorController
實現了一個日誌接口,而Spring AOP採用了JDK動態代理,所以引發了這個異常。
解決方法:
如果不想刪除這個日誌接口,那麼我們可以讓Spring AOP強制使用CGLIB代理。
To force the use of CGLIB proxies set the value of the proxy-target-class
attribute of the <aop:config>
element to true:
要強制使用CGLIB代理,請將<aop:config>
元素的proxy-target-class
屬性的值設置爲true:
<aop:config proxy-target-class="true">
<!-- other beans defined here... -->
</aop:config>
To force CGLIB proxying when using the@AspectJ
autoproxy support, set the 'proxy-target-class'
attribute of the <aop:aspectj-autoproxy>
element to true:
要在使用@AspectJ 自動代理支持時強制CGLIB代理,請將<aop:aspectj-autoproxy>
元素的'proxy-target-class'
屬性設置爲true:
<aop:aspectj-autoproxy proxy-target-class="true"/>