1. 程式人生 > >Spring AOP 和@Autowired 的問題

Spring AOP 和@Autowired 的問題

今天遇到兩個問題。順便做個筆記。以後遇到相同問題可以快速定位。

用的框架是SSH

1、Spring AOP  報錯 org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class.. 

最後找到的原因是 :public final class..  用final修飾了 改類  所以報錯

解釋:

This is a limitation in Spring AOP. When you use AspectJ pointcuts to weave aspects into beans, Spring will use CGLIB to generate a subclass of the target, and invoke the aspects from that subclass.

If the target class does not have a public default constructor, however, this will fail. CGLIB does have the ability to handle this, but this is all hidden behind the Spring AOP stuff and you can't change that behaviour.

I can only suggest that you go back to using setter injection for your controller, rather than constructor injection. It's not ideal, I know, but I can't think of any other workaround. 摘自:http://stackoverflow.com/questions/4490022/error-creating-bean-with-name-org-springframework-web-servlet-mvc-annotation-de

解決:把 final 去掉即可

2、Spring AOP 和@Autowired  衝突。action中@Autowired 不能注入。報空指標問題。

原因暫時不知道,後面如果知道原因。再補上。

解決方法:

方法一、去掉@Autowired,改用set,get注入
方法二、將action納入spring的ioc管理
方法三、修改Struts.xml檔案的屬性<constant name="struts.objectFactory.spring.autoWire.alwaysRespect" value="true" />,使自動注入總是有效(我是用這個方法解決)

解決方法摘自:http://www.2cto.com/kf/201303/198693.html