简体   繁体   English

我可以在无状态会话bean中使用实例变量吗?

[英]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. 我知道无状态bean不会保持会话状态,但我需要的只是一个记录器。 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? 这是肯定的,如果我编写这样的代码,我会在使用logger的某些方法中得到NullPointerException吗?

 @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. 在这种情况下,您甚至可以使用静态类成员添加记录器,并让所有bean实例使用相同的记录器。

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 getInstance()方法,它将提供该类的唯一实例
  4. getLogger() method to get the logger 获取记录器的getLogger()方法

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 您可以在每次需要使用时从getLogger()方法获取记录器

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. 如果你需要线程特定的值,请注意Logger的输出处理程序在每一行写入线程名称,你应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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