Search code examples
javajakarta-eeserializationcdi

@ApplicationScoped must be Serializable?


I am now learning about CDI scope in Java EE 7 tutorial and finding that in the last paragraph it says

Beans that use session, application, or conversation scope must be serializable, but beans that use request scope do not have to be serializable.

But what confused me a lot is that in my IDE (Netbeans and IntelliJ Idea), when I use @SessionScoped or @ConversationScoped, it does give me an error if I am not implementing the Serializable just like what the Java EE 7 tutorial has said, and obviously, I can't build the project then run it. Things get strange when I use @ApplicationScoped but not implementing the Serializable, no errors come out and I can build then run the application normally.

So I'm very curious about that and really want to know why. Could you please explain what happened there? Thank you so much!


Solution

  • The errors in your IDE are showed basically because your IDE has some plugin for this (which is not to be trusted 100% btw).

    The reasons for serialization are as follows:

    • @SessionScoped beans

      • These are handled by more than just CDI spec and other specs have requirements on them
      • Namely, container can choose to store the passivate the session on order to preserve resources
      • Another story is replication between servers so your requests can be handled on several nodes (failover scenario etc.)
      • We don't know why but because of this we must make sure such beans are always serializable
    • @ConversationScoped beans

      • Pretty much the same story, not that other specs would have requirements on them but these bean 'live' within a scope of a session and can live as long as the session (if not ended sooner)
      • For these reasons, when a server passivates/replicates a session along with session scoped beans, it of course has to passivate/replicate conversation scoped beans as well
    • @ApplicationScoped beans

      • These really should be serializable but under certain circumstances, your app will work even when they are not
      • These circumstances being when you can avoid serialization, e.g. running on a single node application server
      • As soon as you need to replicate such bean into several nodes, you need it to be serializable too
      • Another case when serializability can be omitted is in SE
      • Your IDE is therefore smart and does not mandate the Serializable presence