Non-lazy instantiation of CDI SessionScoped beans

↘锁芯ラ 提交于 2019-12-21 23:01:06

问题


CDI newbie question. Simple test scenario: JSF + CDI SessionScoped beans.

I need an elegant way to instantiate a known set of session scoped CDI beans without mentioning them on a JSF page or calling their methods from other beans. As a test case - a simple logging bean, which simply logs start and end time of an http session.

Sure, I could create an empty JSF component, place it inside of a site-wide template and make it trigger dummy methods of the required session beans, but it's kinda ugly from my pov.

Another option I see, is to choose a single session bean (which gets initialized 100% either by EL in JSF or by references from other beans), and use its @PostConstruct method to trigger other session beans - the solution a little less uglier than the previous one.

Looks like I'm missing something here, I'd appreciate any other ideas.


回答1:


Yes, HttpSessionListener would do it. Simply inject the beans and invoke them.

If you container does not support injection in a HttpSessionListener you could have a look at deltaspike core and BeanProvider

http://deltaspike.apache.org/core.html




回答2:


While accepting the Karl's answer and being thankful to Luiggi for his hint, I also post my solution which is based on HttpSessionListener but does not require messing with BeanProvider or BeanManager whatsoever.

@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);
  }
}

To my surprise, the code above instantiates all the beans which methods are observing these events:

@Named
@SessionScoped
public class SessionLogger implements Serializable {

  @PostConstruct
  public void init() {
    // is called first
  }

  public void start(@Observes SessionStartEvent event) {
    // is called second
  }
}


来源:https://stackoverflow.com/questions/19960893/non-lazy-instantiation-of-cdi-sessionscoped-beans

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!