问题
In essence, what is the difference between these two classes:
@ApplicationScoped
@Singleton
class A {}
@Dependent
@Singleton
class B {}
Contextual EJB instances
I prefer not to use @Inject when looking for EJB:s, unless the EJB is a @Stateful and I want the CDI container to manage the stateful's life-cycle which could be very convenient. Otherwise, using @Inject to retrieve a contextual EJB instance is a bit dangerous. For example, a @Remote client-view cannot be retrieved using CDI unless we also write a producer. Furthermore, class A and class B can not declare any other scope than what they currently do. CDI 1.1, section "3.2 Session beans" says:
A singleton bean must belong to either the @ApplicationScoped scope or to the @Dependent pseudo-scope. If a session bean specifies an illegal scope, the container automatically detects the problem and treats it as a definition error.
Hence, apart from stateful beans, I see no point in using CDI when I go look for EJB:s.
A more mature version of the question
From the client code's perspective which uses @Inject to declare a dependency on either A or B, I cannot imagine there is a difference. In both cases, the call will be routed to a singleton EJB. Had I been the implementation author of a CDI provider, then I might even inject the real EJB proxy in both cases and ignore future calls asking for destruction of the dependent CDI proxy? The bottom line is that we may declare two different scopes on the EJB singleton class. So what's the difference?
来源:https://stackoverflow.com/questions/28926854/dependent-javax-ejb-singleton-versus-applicationscoped-javax-ejb-singleton