注入的另一个 CDI bean 是否需要 @DependsOn?

Is @DependsOn necessary for another CDI bean that is injected?

给定两个用@Startup 注释的 bean:

@Singleton    
@Startup
@DependsOn("B")
public A {
  @Inject
  private B b;
}

@Singleton    
@Startup
public B {}

在这种情况下是否需要@DependsOn 来确保B 在A 之前被初始化?或者是否有一些关于配置的约定,在这种情况下注入的顺序决定了初始化的顺序?

官方教程没有涵盖这种情况,只涵盖了仅在语义上没有任何 syntactic/wiring link 通过 @Inject 的 bean。

是的,有必要。

否则无法保证 B 会在 A 之前初始化。

根据 JavaEE 6 documentation:

Sometimes multiple singleton session beans are used to initialize data for an application and therefore must be initialized in a specific order. In these cases, use the javax.ejb.DependsOn annotation to declare the startup dependencies of the singleton session bean. The @DependsOn annotation’s value attribute is one or more strings that specify the name of the target singleton session bean. If more than one dependent singleton bean is specified in @DependsOn, the order in which they are listed is not necessarily the order in which the EJB container will initialize the target singleton session beans.

示例:

应首先启动以下单例会话 bean PrimaryBean

@Singleton
public class PrimaryBean { ... }

SecondaryBean 取决于 PrimaryBean:

@Singleton
@DependsOn("PrimaryBean")
public class SecondaryBean { ... }

这保证 EJB 容器将在 SecondaryBean 之前初始化 PrimaryBean

如果 bean A 实际上依赖于被初始化的 bean B,那么你需要这个。

使用@Startup,您正在执行急切的实例化——单例在启动时实例化,无论它是否被使用。

在惰性实例化中,单例只有在第一次需要它的方法时才会被实例化。

在这两种情况下,容器都可以按照它想要的任何顺序初始化 bean:

有时,多个单例会话 bean 用于为应用程序初始化数据,因此必须按特定顺序进行初始化。在这些情况下,使用 javax.ejb.DependsOn 注释来声明单例会话 bean 的启动依赖项。