我有一个CDI bean,我正在使用@ConversationScoped。当我尝试为Conversation对象执行@Inject时,我得到一个NPE。
@ConversationScoped
@Named("customerbean")
public class CustomerBean implements Serializable {
@Inject
private Conversation conversation;
private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("ba");
private EntityManager em;
private Customer customer;
boolean disabled;
public CustomerBean() {
beginConversation();
customer = new Customer();
em = emf.createEntityManager();
disabled = false;
}
private void beginConversation() {
if (this.conversation.isTransient()) {
this.conversation.begin();
return;
}
throw new IllegalStateException();
}
我在WEB-INF目录中有beans.xml文件(尽管是空的)。例外情况如下:
INFO: Exception when handling error trying to reset the response.
com.google.common.collect.ComputationException: java.lang.RuntimeException: java
.lang.NullPointerException
at com.google.common.collect.ComputingConcurrentHashMap$ComputingMapAdap
ter.get(ComputingConcurrentHashMap.java:397)
at org.jboss.weld.bean.proxy.ClientProxyProvider.getClientProxy(ClientPr
oxyProvider.java:102)
at org.jboss.weld.el.AbstractWeldELResolver.lookup(AbstractWeldELResolve
r.java:115)
at org.jboss.weld.el.AbstractWeldELResolver.getValue(AbstractWeldELResol
ver.java:96)
at org.jboss.weld.environment.servlet.util.ForwardingELResolver.getValue
(ForwardingELResolver.java:49)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELR
esolver.java:176)
答案 0 :(得分:6)
您不能使用new
创建CDI bean,也不能将构造函数用于任何类型的初始化逻辑。
这背后的原因是CDI bean(如EJB,Spring bean,JSF bean)具有独立的生命周期,并由相关容器管理。你不能依赖于对new
何时(以及多久)调用的“传统”理解。使用producer来创建新bean,并使用@PostConstruct
来创建任何逻辑。
This应该为您提供CDI的良好开端。随意发表更多问题:)
答案 1 :(得分:0)
正如Jan所说,你在构造函数中添加了逻辑。直到调用构造函数之后才会发生注入。