Reputation: 4454
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.
Upvotes: 3
Views: 747
Reputation: 4454
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
}
}
Upvotes: 3
Reputation: 2435
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
Upvotes: 1