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!
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
@ConversationScoped
beans
@ApplicationScoped
beans
Serializable
presenceSerializable marker is one of the required attributes for beans, that are passivation capable(able to transform from active state to some kind of second inactive state). A bean must be passivation capable, if it has a passivating scope(scope with attribute passivating=true
). According to CDI spec 1.1. only Session
and Conversation
scope are passivating scopes.
Chapter 6.6.4 Passivating scopes For example, the built-in session and conversation scopes defined in Section 6.7 are passivating scopes. No other built-in scopes are passivating scopes.
Therefore your session beans need to be passivation capable -ergo need to be Serializable, but your Application scoped beans needs not. Also, some CDI containers will not throw the error on missing Serializable
on session scoped beans during deployment, but only at the time when they actually need to transfer the bean instance from active state to passive state(e.g. instance limit has been hit, memory usage, etc)
For more info just read the CDI 1.1 spec.
Happy hacking
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With