单例注入顺序

Singleton injection order

我有以下内容:

@Singleton
public class A {
   @Inject
   private B b;

   @PostConstruct
   void initialize(){
     b.someMethod();
   }
}

@Singleton
public class B {

}

我们能确定 B 总是在 A 之前注入吗?

来自 EJB 3.1 规范的 §4.8.1:

In some cases, explicit initialization ordering dependencies exist between multiple Singleton components in an application. The DependsOn annotation is used to express these dependencies. A DependsOn dependency is used in cases where one Singleton must initialize before one or more other Singletons. The container ensures that all Singleton beans with which a Singleton has a DependsOn relationship have been initialized before PostConstruct is called.

Note that if one Singleton merely needs to invoke another Singleton from its PostConstruct method, no explicit ordering metadata is required. In that case, the first Singleton would merely use an ejb reference to invoke the target Singleton. There, the acquisition of the ejb reference (either through injection or lookup) does not necessarily imply the actual creation of the corresponding Singleton bean instance.

...