为什么 CDI 不能在单例中工作 class

Why the CDI is not working in a singleton class

单例 class 正在触发事件,但容器未调用 CDI 事件侦听器。

下面,DataLoaderSessionBean 单例中的 creatData() class 调用 loadUsers() 方法,然后 loadUsers() 触发一个事件,该事件假设调用 XMLDataListener.UserData() 但是电话永远不会发生。但是,如果我将 class 从单例更改为有状态或无状态会话 bean,则一切正常。

@Record
@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)

public class DataLoaderSessionBean {

    @Inject
    @UserXMLData
    Event<DataEvent> userData;
    
    private final static int LOAD=0;

    private void loadUsers() {
        DataEvent event = new DataEvent();
        event.setCommand(LOAD);
        userData.fire(event);
    }
    
    @PostConstruct
    public void createData() {
        loadUsers();
        .........
    }
}

这是事件侦听器。容器未调用此事件侦听器 class 上的 userData() 方法。

@Record
@SessionScoped
public class XMLDataListener implements Serializable {

    private static final long serialVersionUID = -2230122751970858111L;
    private final static int LOAD=0;
    public void UserData(@Observes @UserXMLData DataEvent event) {
        int cmd = event.getCommand();
        switch(cmd){
            case LOAD: loadUsers();
            break;
            ..........
            
        }
    }
}

侦听器接口:

@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface UserXMLData {
}

事件数据

public class DataEvent implements Serializable {
    
   private static final long serialVersionUID = -2230122751970857224L;
   private int command;

    public DataEvent() {
    }

    public int getCommand() {
        return command;
    }

    public void setCommand(int command) {
        this.command = command;
    }   
}

知道为什么此功能适用于会话 bean 而不适用于单例吗?

谢谢

这是 CDI 2.0 规范第 10.5 节要求的行为

If there is no context active for the scope to which the bean
declaring the observer method belongs, then the observer method
should not be called.

单例的 @PostConstruct 方法在应用程序上下文启动时调用,因此没有活动会话。 要触发观察者方法 XMLDataListener 应该用 @ApplicationScoped.

注释声明