在接受卡尔的回答并感谢 Luiggi 的提示的同时,我还发布了我的解决方案,该解决方案基于HttpSessionListener
但不需要弄乱BeanProvider
或BeanManager
任何东西。
@WebListener
public class SessionListener implements HttpSessionListener {
@Inject
Event<SessionStartEvent> startEvent;
@Inject
Event<SessionEndEvent> endEvent;
@Override
public void sessionCreated(HttpSessionEvent se) {
SessionStartEvent e = new SessionStartEvent();
startEvent.fire(e);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
SessionEndEvent e = new SessionEndEvent();
endEvent.fire(e);
}
}
令我惊讶的是,上面的代码实例化了所有方法正在观察这些事件的 bean:
@Named
@SessionScoped
public class SessionLogger implements Serializable {
@PostConstruct
public void init() {
// is called first
}
public void start(@Observes SessionStartEvent event) {
// is called second
}
}