@Injection对CDI bean不起作用 [英] @Injection is not working for CDI bean

查看:71
本文介绍了@Injection对CDI bean不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用@ConversationScoped的CDI bean.当我尝试为对话对象执行@Inject时,我得到了NPE.

I have a CDI bean where I'm using @ConversationScoped. When I try to do an @Inject for the Conversation object, I get a 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文件(尽管为空).异常看起来像这样:

I have the beans.xml file (although empty) in the WEB-INF directory. The exception looks like this:

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)

推荐答案

不得使用new创建CDI bean,也不得针对任何类型的初始化逻辑使用构造函数.

You must not create a CDI bean using new, nor use a constructor for any sort of initialization logic.

其背后的原因是CDI Bean(如EJB,Spring Bean,JSF Bean)具有独立的生命周期,并由相关的容器进行管理.您不能依靠传统"理解何时将调用new(以及调用频率).使用生产者创建新的bean,并使用@PostConstruct进行创建后要执行的任何逻辑.

The reason behind this is that CDI beans (like EJBs, Spring beans, JSF beans) have an independent lifecycle and are managed by the relevant container. You cannot rely on the "traditional" understanding of when (and how often) new will be called. Use producers to create new beans, and use @PostConstruct for any logic to be performed after creation.

应该为您提供CDI的良好入门.随时发表进一步的问题:)

This should give you a good start with CDI. Feel free to post further questions :)

这篇关于@Injection对CDI bean不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆