I have a EJB that needs to be a singleton and stateful since its going to be a sort of connection pool. My questions are:
@Singleton
annotation, will it then be stateful by default or do I have to define it with @Stateful
also?@Stateless
annotation?Tried to find some documentation about this but no luck so far so anyone with knowledge please share your wisdom and perhaps a link or two.
The EJB tutorials show that an EJB can be either Singleton or Stateful or or Stateless. I have never tried to use more than one of these annotations, but I am fairly convinced that the right thing to do is to use only one of them.
From that link:
Singleton session beans maintain their state between client invocations
So, to your question:
if I define a EJB with @Singleton annotation will it then be stateful by default or do I have to define it with @Stateful also?
If for Stateful you mean the ability to maintain its state, the answer is: yes, a Singleton will be Stateful by default.
Keep in mind that there are some particular situations in which a Singleton doesn't behave like a Singleton, read this article about this. Generally, you don't run this kind of risk if you are outside of a cluster and avoid using the default constructor: you need to always use references of an EJB by injecting it in another EJB or a web client using:
@EJB MyEJB myEJB;
Finally, have a look at this part of the Java EE 6 tutorial, about EJBs lifecycle, explaining that the main difference between Stateful and other EJBs is the ability to being passivated by the container during its life. This difference is the main reason why the statement "a Singleton is Stateful by default" is not correct strictly speaking, but is correct in the context of your question.
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