javax.enterprise.event.Event:如何初始化pushEvent

时间:2012-12-18 15:48:48

标签: java events push cdi

我目前正在工作CDI pushevent。我计划通过后端Java代码触发pushevent,而不是通过commandButton触发前端jsf。 这是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);
                     }
}
你可以给我一些建议吗?非常感谢你。

1 个答案:

答案 0 :(得分:1)

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