Spring Injection - access to the injected object within a constructor

ぃ、小莉子 提交于 2019-12-23 08:04:20

问题


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
   }
}

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?


回答1:


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.

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
}



回答2:


The reason is in the lifecycle of the bean:

  • The container (spring application context) instantiates the object
  • then it sets all the dependencies (incl. the entityManager in your example)
  • after all dependencies have been set, it invokes the @PostConstruct method, if any.

Spring (and no one) can set fields to an object before actually constructing that object.

You can use constructor-injection - passing the dependencies to a non-default constructor, but it is not possible with @PersistenceContext



来源:https://stackoverflow.com/questions/4134493/spring-injection-access-to-the-injected-object-within-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!