我有一个资源(Spring bean),它的一些字段是由 Spring 注入的,例如:
@Repository(value="appDao")
public class AppDaoImpl implements AppDao {
@PersistenceContext
EntityManager entityManager;
public Resource() {
... use entityManager ... // doesn't work
}
}
我知道我无法访问构造函数中注入的entityManager,应该使用@PostConstruct
对不同方法的注释。但这是什么原因呢?
因为Spring在创建对象之前无法访问任何字段或方法(这是通过构造函数完成的)。所以Spring使用构造函数实例化对象并then注入属性。
解决这个问题的唯一方法是使用构造函数注入 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-class-ctor(如果您有多个依赖项,这可能会很麻烦)。我认为你应该做的是将你的代码从构造函数中移出并使用初始化方法the @PostConstruct注解 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-postconstruct-and-predestroy-annotations:
@PostConstruct
public void init(){
// do stuff with entitymanager here
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)