I have unresolved question about CDI:
I have Producer class annotated with @ApplicationScoped and the @Produce method has no additional scope annotaion.
@ApplicationScoped
public class SecurityIdentityProducer {
public SecurityIdentityProducer() {
}
@Produces
public SecurityIdentity getSecurityIdentity() {
return SecurityIdentityImpl();
}
}
Will be the method getSecurityIdentity() invoked for each injection point, or will be the result from first invocation be reused?
In order to invoke getSecurityIdentity() for every injection point, do I have to annotate that method with @RequestScoped like this?
@Produces
@RequestScoped
public SecurityIdentity getSecurityIdentity() {
return SecurityIdentityImpl();
}
Or does it depend on scope of the Bean where injection is taking place?
So for example the behavior won't be the same for a @Singleton Bean and for @Stateless Bean?
Thank you ofor clarification.
Best regards Dalibor
A producer method (or a producer field) behaves similarly to a class-based bean. Unless you explicitly declare a scope, @Dependent
is assumed.
For ease of understanding, think of producers as bean declarations - you need to declare a scope and qualifier(s) just as you would with a class-based bean.
In your first code example, the SecurityIdentity
bean is therefore a @Dependent
bean and as such the producer will be invoked for every injection point.
Note that @Dependent
beans behave differently to other scopes where beans are created once within the context and "live" as long as the context does. The lifecycle of dependent beans is bound to whichever bean you inject them into and dependent bean instances are not shared.
This leads me to the last part of your question - using @RequestScoped
. With that configuration, the bean would be created at most once for each request (the same instance shared between injection points), and destroyed along with the request ending.