Spring Injection-访问构造函数中的注入对象 [英] Spring Injection - access to the injected object within a constructor
问题描述
我有一个资源(Spring bean),其中有一些由Spring注入的字段,例如:
I have a resource (Spring bean) which has some of its fields injected by Spring, for example:
@Repository(value="appDao")
public class AppDaoImpl implements AppDao {
@PersistenceContext
EntityManager entityManager;
public Resource() {
... use entityManager ... // doesn't work
}
}
我知道我无法在构造函数中访问注入的entityManager,应该使用 @PostConstruct
在其他方法上的注释。但这是什么原因呢?
I know that I can't access the injected entityManager in the constructor and should use a @PostConstruct
annotation on a different method. But what are the reasons for this?
推荐答案
因为在创建对象之前,Spring无法访问任何字段或方法(通过构造函数完成)。因此,Spring使用构造函数实例化对象,然后然后注入属性。
Because Spring can't access any fields or methods before the object is created (which is done through the constructor). So Spring instantiates the object using the constructor and then injects the properties.
唯一的解决方法是使用构造函数注入(如果您有多个依赖项,可能会很麻烦)。我认为您应该做的是使用 @PostConstruct
注释:
The only way around this is to use Constructor Injection (which can be cumbersome if you have multiple dependencies). I think what you should do is move your code out of the constructor and into an initialization method using the @PostConstruct
annotation:
@PostConstruct
public void init(){
// do stuff with entitymanager here
}
这篇关于Spring Injection-访问构造函数中的注入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!