Is @DependsOn necessary for another CDI bean that is being introduced?

Given the two beans annotated with @Startup:

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

Is @DependsOn necessary in this situation to ensure that B initializes to A? Or is there some kind of conditional configuration that, in such a situation, the order of injection determines the order of initialization?

The official guide does not cover this case, but only beans that are simply semantically covered without syntactic / wire communication via @Inject.

+5
source share
2 answers

If bean A actually depends on the initialization of bean B, you need it.

With @Startup, you make an impatient moment - a singleton is created at launch time, regardless of whether it is used.

In a lazy instantiation, a singleton is not created until its method is needed.

In both cases, the container can initialize beans depending on what it wants:

Sometimes, several single beans sessions are used to initialize data for an application, so they need to be initialized in a specific order. In these cases, use the javax.ejb.DependsOn annotation to declare dependencies for starting a single-user bean session.

+1
source

Yes, it is necessary.

Otherwise, nothing guarantees that B will be initialized to A

According to JavaEE 6 documentation :

Sometimes, several single beans sessions are used to initialize data for an application, so they need to be initialized in a specific order. In these cases, use the javax.ejb.DependsOn annotation to declare dependencies for starting a single-user bean session. The value @DependsOn annotations attribute is one or more lines that define 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 initializes the target singleton beans session.

Example:

First, start the following bean PrimaryBean session, PrimaryBean :

 @Singleton public class PrimaryBean { ... } 

SecondaryBean depends on PrimaryBean :

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

This ensures that the EJB container initializes the PrimaryBean to SecondaryBean .

+1
source

All Articles