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

3.6k views Asked by At

Given two beans annotated with @Startup:

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

@Singleton    
@Startup
public B {}

Is @DependsOn neccessary in this situation to ensure that B is initialized before A? Or is there some convention over configuration that in such a situation the order of injections determines the order of initialization?

The official tutorial does not cover this case but only beans that are merely semantically covered without any syntactic/wiring link via @Inject.

2

There are 2 answers

0
John On BEST ANSWER

If bean A actually depends on bean B being initialized then you need this.

With @Startup you are doing eager Instantiation - the singleton is instantiated at startup time whether or not it gets used.

In lazy instantiation, the singleton isn't instantiated until it's method's are first needed.

In both cases, container can initialize beans at whichever order it wants:

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.

2
Konstantin Yovkov On

Yes, it's necessary.

Otherwise nothing guarantees that B will be initialized before A.

According to the 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.

Example:

The following singleton session bean, PrimaryBean, should be started up first:

@Singleton
public class PrimaryBean { ... }

SecondaryBean depends on PrimaryBean:

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

This guarantees that the EJB container will initialize PrimaryBean before SecondaryBean.