我试图向实现单例模式的类中注入日志记录器对象。
代码大致如下:
Logger 类:
然后我创建了一个需要日志记录器并实现单例模式的类:
代码大致如下:
Logger 类:
public class LoggerFactory {
@Produces
public Logger getLogger(InjectionPoint caller){
return Logger.getLogger(caller.getMember().getDeclaringClass().getName());
}
}
然后我创建了一个需要日志记录器并实现单例模式的类:
public class MySingleton{
@Inject
private Logger logger;
private MySingleton instance;
/*
* Private constructor for singleton implementation
*/
private MySingleton(){
logger.info("Creating one and only one instance here!");
}
public MySingleton getInstance(){
if(instance == null) {
instance = new MySingleton();
}
return instance;
}
}
如果我运行代码(在Glassfish 3.1.2.2上),一旦尝试使用日志记录器,就会出现NPE。我做错了什么(beans.xml
文件已经放置好了)?我还尝试使用@Inject
和Logger
对象的setter方法,但没有成功。
@Singleton
来指示 CDI 容器始终注入相同的 bean 实例。 - Perception