0

我目前正在工作 CDI pushevent。我计划通过后端 Java 代码而不是通过 commandButton 来触发前端 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);
                     }
}

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

4

1 回答 1

1

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

于 2012-12-19T14:07:53.840 回答