我正在尝试将记录器对象注入到按照单例方法实现的类中。
代码几乎是这样的:
Logger
class:
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
使用 setter 方法Logger
对象但没有运气。
注射发生在构建之后。所以你不能在构造函数中使用它。
一种方法是添加一个注释为 @PostConstruct 的方法,该方法可以在注入后调用。
@PostConstruct
public void init() {
logger.info("Creating one and only one instance here!");
}
顺便说一句,我认为您处理问题的方式是错误的。 CDI 有很好的单例支持
创建一个带@Singleton注释的类
@Singleton
public class MySingleton {
@Inject
Logger logger;
@PostConstruct
public void init() {
logger.info("Creating one and only one instance here!");
}
}
上面假设您正在使用 CDI for java ee (JSR-299)。
如果您使用 JSR 330 依赖注入(guice 等)link http://matthiaswessendorf.wordpress.com/2010/01/19/dependency-injection-the-jsr-330-way/
您可以使用构造函数注入:
@Singleton
public class MySingleton {
private final Logger logger;
@Inject
public MySingleton (Logger logger) {
this.logger = logger;
logger.info("Creating one and only one instance here!");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)