Valid CDI scopes for Session (EJB) beans

CDI enriches the EJB specification (Session beans to be specific) by providing contextual life cycle management. Session beans are not ‘contextual’ instances in general.

If you are comfortable with CDI in general, the idea of ‘being contextual’ should be pretty clear.

Here are the valid permutations and combinations of EJB session beans and corresponding CDI scopes (Application, Session or Request)

  • Stateless beans can only belong to the @Dependent scope i.e. you can either choose to use the @Dependent pseudo-scope explicitly or just flow with the @Stateless annotation in which case the CDI container will pretty much use @Dependent by default (convention).

The CDI container will not let you get away with any other annotation and the end result would be a deployment failure

  • With Singleton beans, @ApplicationScoped is the only valid CDI scope (@Dependent is the default in case you do not use any other explicit CDI scope)

Again, any other scope annotation and the CDI god will crush your WAR/EAR !

  • Stateful EJBs can have any scope – no restrictions whatsoever! (although I do not see too much value in using @ApplicationScoped for Stateful beans – but that’s just me! feel free to chime in case you think otherwise)

Stay safe !

About Abhishek

Currently working as a Senior Product Manager in the Oracle Cloud Application Development team with a focus on Oracle Cloud PaaS portfolio. When not hovering in the clouds, I stay grounded with Java EE
This entry was posted in Java, Java EE and tagged , , , , , . Bookmark the permalink.

3 Responses to Valid CDI scopes for Session (EJB) beans

  1. Patrik says:

    Thanks, this post filled a gap and was exactly what I was looking for!

    I’m not sure if I have understood correctly but why don’t you see any point with @Stateful combined with @ApplicationScoped? Do you mean that it’s practically the same as @Singleton (possibly combined with @ApplicationScoped)?

    I made a fast experiment. I have a @ViewScoped bean injecting a service into it:

    Service with just @Stateful: The service defaults to view scope.
    Service with @Stateful and @ApplicationScoped: The service becomes application scoped.

    So @ApplicationScoped changes things here, so why don’t you recommend that combination?



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s