以单例模式使用CDI [英] Using CDI in a singleton pattern
问题描述
我正在尝试在一个按照单例方法实现的类中注入一个logger对象。
I'm trying to inject a logger object in a class that is implemented following a singleton approach.
代码几乎如下所示:
记录器
类:
public class LoggerFactory {
@Produces
public Logger getLogger(InjectionPoint caller){
return Logger.getLogger(caller.getMember().getDeclaringClass().getName());
}
}
然后我创建一个需要记录器的类并实现单例模式:
Then I create a class that needs logger and implements the Singleton Pattern:
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
对象,但没有运气。
If I run the code (on Glassfish 3.1.2.2) I get a NPE as soon as I try to use the logger.
What I'm doing wrong (beans.xml
file is in place)?
I've also tried using @Inject
with a setter method for the Logger
object but with no luck.
推荐答案
在构造之后进行注射。所以你不能在构造函数中使用它。
Injections happens after construct. So you cant use it in the constructor.
一种方法是添加一个带注释的@PostConstruct方法,可以在注入后调用它。
One way is to add a method annotated @PostConstruct that can will be invoked after injections.
@PostConstruct
public void init() {
logger.info("Creating one and only one instance here!");
}
在旁注上我认为你正以错误的方式解决问题。 CDI有一个很好的单身人士支持
On a sidenote i Think you are aprouching the problem in the wrong way. CDI has a nice singleton support
创建一个带注释的类@Singleton
create a class annotated @Singleton
@Singleton
public class MySingleton {
@Inject
Logger logger;
@PostConstruct
public void init() {
logger.info("Creating one and only one instance here!");
}
}
以上假设您使用的是CDI java ee(JSR-299)。
Above assumes you are using CDI for java ee (JSR-299).
如果您正在使用JSR 330依赖注入(guice等) link
If you are using JSR 330 Dependency Injection (guice etc.) link
你可以使用构造函数注入:
You could use constructor injection:
@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!");
}
}
这篇关于以单例模式使用CDI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!