Is it possible to inject a request-scoped CDI bean into a Stateless session bean?
I had asked a related question and thought the specific CDI @RequestScoped into @Stateless question merited its own post.
Passing state between EJB methods / @RequestScoped and @Stateless
I also asked a similar question about JMS @MessageDriven beans – basically want to know the same about @Stateless.
You can absolutely do what you mention and use
@RequestScopedbeans in an@Statelesssession bean and an@MessageDrivenbean. This is a core part of the CDI spec and TCK and guaranteed portable.Note on MDBs
Do be aware that there is a test for a
@Statelessbean that uses a@RequestScopedbean, but there is no test that guarantees a@MessageDrivenbean can reference@RequestScopedbeans. This was just an oversight and is already fixed for the Java EE 7 TCK. So just be aware that if it doesn’t work for the MDB case, it may not be your fault 🙂The workaround would be to simply have your MDB delegate to a SessionBean of any kind as
@Stateless,@Stateful, and@Singletonall have@RequestScopedtests.Making the EJB, itself, scoped
While
@Stateless,@Singletonand@MessageDrivencan have scoped references injected via@Inject, they cannot be@RequestScopedor any other scope. Only the@Statefulmodel is flexible enough to support scopes. In other words, you can annotate the@Statefulbean class itself as@RequestScoped,@SessionScoped, etc..In simple terms
@Stateless,@Singletonhave fixed "scopes" already.@Singletonis essentially@ApplicationScopedand@Statelesswould perhaps be some made-up scope like@InvocationScoped, if that existed. The lifecycle of an@MessageDrivenbean is entirely up to the Connector that drives it and is therefore also not allowed to have user-defined scope.