views:

179

answers:

3

Time and again, I read that we are not supposed to use static variables in a session bean. Then, how am I supposed to get a logger for this bean and use it all over the bean methods ?

+1  A: 

You can just make it a non-static member.

laz
+6  A: 

I think you are interpreting the "rule" a little too rigidly.

You shouldn't store any sort of state of a servlet/session/bean in a static variable, as that reference is shared amongst all instances of that type.

However, a logger (usually, or shouldn't) hold any state. It's perfectly fine IMO to use static references to a Logger instance, if you follow the usual practice of naming/categorizing your loggers based on the classname:

public class SomeTypeOfBean {
    private static final Logger log = Logger.getLogger(SomeTypeOfBean.class);
    //...
}
matt b
+3  A: 

Read only non-blocking static references (which is what a logger is) are generally fine, if there are no issues with having a few copies of them around (at the application server's discretion).

That being said, there is nothing that says that a logger must be in a static variable. It can be in an instance variable (and a transient one at that if your logger is not serializable).

One thing to realize with the EJB rules - it is most important to understand why they exist and what could trip up an app server (if you are indeed developing app server independent). Once you understand that, you know how to work with them (and they make sense given what an app server is expected to do with your class). If it is just a bunch of arbitrary rules written on a document, then you won't be able to figure out how to work with them, instead of getting trapped by them.

Yishai