简体   繁体   中英

Can I use instance variables in stateless session bean?

I know that stateless bean doesn't maintain conversational state but what I need is just a logger. Should I get logger in every method which is called? If not then where should I initialize it?

Is that's for sure that if I write such code I won't get NullPointerException in some method which uses logger?

 @PostConstruct
 public void init() {
   logger = Logger.getLogger();
 }

I guess you'd not want to have a request/session specific logger, right? In that case you could even use a static class member to add the logger and let all bean instances use the same logger.

Create a singleton class which will have the following properties:

  1. Static field with the type of the class itself
  2. Private constructor to insure that only one instance of this logger class is initiated
  3. getInstance() method which will give the only instance of the class
  4. getLogger() method to get the logger

Initialize the logger in the constructor of this class and
You can get the logger from the getLogger() method every-time you need to use it

Try:

private static final Logger log = Logger.getLogger();

If you need Thread specific values take care that the output handler of the Logger writes the Thread name in every line and you should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM