Can I use instance variables in stateless session bean?
-
01-06-2021 - |
Question
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();
}
Solution
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.
OTHER TIPS
Create a singleton class which will have the following properties:
- Static field with the type of the class itself
- Private constructor to insure that only one instance of this logger class is initiated
getInstance()
method which will give the only instance of the classgetLogger()
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.