I'm following this tutorial which also uses an EJB:
package exercise1;
import java.util.Random;
import javax.ejb.Stateless;
import javax.inject.Named;
@Stateless
public class MessageServerBean {
private int counter = 0;
public String getMessage(){
Random random = new Random();
random.nextInt(9999999);
int myRandomNumber = random.nextInt();
return "" + myRandomNumber;
}
public int getCounter(){
return counter++;
}
}
Here is an output example:
Hello from Facelets
Message is: 84804258
Counter is: 26
Message Server Bean is: exercise1.MessageServerBean@757b6193
Here's my observation:
- When I set the bean as
@Stateless
I always get the same object ID and counter always increments. - When I set the bean as
@Stateful
I get a new instance every time I refresh the page. - When I set it to
@Singleton
I get the same results as when I set it to@Stateless
: same object ID, counter incrementing.
So, what I actually would like to understand is: what's the difference between @Stateless
and @Singleton
EJBs in this very case?