I'm new in EJB. I heard that in some cases it is acceptable to store some information (such as configurations) in stateless beans. As I understand the stateless bean lifecycle begin on bean's method invocation and end on method conclusion. After method ends up the stateless bean will be returned to the pool.
@Stateless
public class MyBean {
private String config = ....;
//.....
}
Thank you in advance.
The private String config = ...
will be ininialized only once for every instance of a bean, when it is created (usually during application startup, but also possible when the application server decides that more beans are needed to handle growing traffic).
Basically, when you execute a public bean's method, you're guaranteed to be the sole executor of that bean instance. During that time you're allowed to store anything in private variables. Once you return to the code that called your bean, though, you're never guaranteed that subsequent calls will be directed to the same instance.
Example:
@Stateless
public class MyBean implements MyBeanIntf {
private Object state;
@Override
public void beanMethod() {
state = new Object();
privateMethod();
}
private void privateMethod() {
// it's safe to access 'state' here, will be the one set in
// beanMethod()
}
@Override
public void otherMethod() {
}
}
@Stateless
public void MyBeanClient {
@EJB
private MyBean myBean;
someMethod() {
myBean.beanMethod();
// Not necessarily the same instance that executed beanMethod
// will execute otherMethod
myBean.otherMethod();
}
}
That's theory. In practice, I'd avoid code that relies on keeping internal temporary state in a stateless EJB -- just because this style suggest to other programmers that it's OK to have state of an SLSB in general, which leads to confusing code and potential errors (esp. if state from previous executions is mistakenly picked up as the current one).