我目前正在从事CDI pushevent。我计划通过后端Java代码而不是由commandjs触发前端jsf来触发pushevent。
这是PushCdiBean.java的代码

import java.io.Serializable;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.enterprise.event.Event;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;



import org.richfaces.application.push.MessageException;
import org.richfaces.application.push.TopicKey;
import org.richfaces.application.push.TopicsContext;
import org.richfaces.cdi.push.Push;

/**
 * @author <a href="http://community.jboss.org/people/lfryc">Lukas Fryc</a>
 */
@javax.inject.Named("pushCdiBean")
@javax.enterprise.context.RequestScoped
//@ManagedBean(name="pushCdiBean")
//@ViewScoped


public class PushCdiBean implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -5241937306040858158L;
    private static final String CDI_PUSH_TOPIC = "pushCdi";
    private String userIdentifier;
    private String message;

    @Inject
    @Push(topic=CDI_PUSH_TOPIC)//i thought that the topic is initialized with this ?!
    private Event<String> pushEvent;

    @PostConstruct
    public void initialize() {
                   if(userIdentifier == null) {
                                  userIdentifier = UUID.randomUUID().toString().replace("-", "");
                   }

    TopicsContext topicsContext = TopicsContext.lookup();
    topicsContext.getOrCreateTopic(new TopicKey(CDI_PUSH_TOPIC, userIdentifier));//initialize the topic and make the troublesome message disappears
    }

    public synchronized void sendMessage() throws MessageException {
              pushEvent.fire(message);
    }


    public String getMessage() {
              return message;
    }


    public void setMessage(String message) {
              this.message = message;
    }

    public Event<String> getPushEvent() {
        return pushEvent;
    }

    public void setPushEvent(Event<String> pushEvent) {
        this.pushEvent = pushEvent;
    }

    public String getUserIdentifier() {
        return userIdentifier;
    }

    public void setUserIdentifier(String userIdentifier) {
        this.userIdentifier = userIdentifier;
    }


但是,当我尝试创建PushCdiBean类并调用sendMessage()函数时,pushEvent.fire失败。
代码在这里。

/**
 *
 */
public void run() {
      while (running) {
            try {
                            PushCdiBean pushTest = new PushCdiBean();
                            pushTest.setMessage("This is CDI push Test");
                            pushTest.sendMessage();
                         }
                         catch (Exception e) {
                    System.out.println("Exception: " + e.getMessage());
                          }
                       sleep(4000);
                     }
}


你能给我一些建议吗?非常感谢你。

最佳答案

您必须@Inject CDI bean,而不是自己通过new实例化它。

关于java - javax.enterprise.event.Event:如何初始化pushEvent,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13936582/

10-10 17:10