简体   繁体   English

春豆初始化顺序

[英]Spring Bean Init Order

I have two Spring Beans as follows: 我有两个Spring Bean,如下所示:

@Service
public class A{
}

@Service
public class B{
   @Autowired A a;

   public B(){
      a.doSomething();
   }

The problem is that it is not guareenteed that A will be init earlier than B. So I will get a NullPointerException in B(). 问题是不保证A的初始化早于B。所以我将在B()中得到NullPointerException。

Is there anyway that I can specify this dependency in Spring? 无论如何,我可以在Spring中指定此依赖项吗?

Any autowiring in Spring framework will happen after the bean has been constructed. 在构造完bean 之后 ,Spring框架中的任何自动装配都将发生。 Therefore, it is not possible to use autowired members from the constructor itself (as seen in Autowired javadoc page ). 因此,无法使用构造函数本身中的自动装配成员(如自动装配javadoc页面中所示 )。 Your options are to either put the annotation on the constructor itself and make it accept the other bean as parameter which wil then work: 您的选择是将注释放在构造函数本身上,并使其接受另一个bean作为参数,然后将起作用:

@Service
public class B {

  @Autowired
  public B(A a) {
     a.doSomething();
  }
}

or to use the @PostConstruct annotation on a separate method which will be guaranteed to execute after the bean is constructed and will have all references wired correctly: 或在单独的方法上使用@PostConstruct批注,该批注将确保在构造bean之后执行并正确连接所有引用:

@Service
public class B{

  @Autowired
  A a;

  @PostConstruct
  public moreSetup() {
     a.doSomething();
  }
}

Spring is capable of detecting these dependencies automatically. Spring能够自动检测这些依赖关系。 It knows to create A before B based on the @Autowired annotation (or more formally - when creating the instance of B, Spring detects that it needs an A, and will instantiate the A if it has not done so already). 它知道基于@Autowired注释在B之前创建A(或更正式地讲-在创建B的实例时,Spring检测到它需要A,如果尚未这样做,则将实例化A)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM