这是我当前的场景:
@WebListener
public class WebListenerService implements HttpSessionListener{
.... implement methods
@Produces
@Dependent
public SessionDependentService sessionDependentService(){
}
}
@SessionScoped
@Named
public class AccountController implements Serializable{
//Injected properly and works as expected
@Inject
private SessionDependnetService sessionDependentService;
@Inject
@OnLogin
private Event<Account> accountEvent;
public void onLogin(){
accountEvent.fire(authenticatedAccount);
}
}
@SessionScoped
public class AccountObserver implements Serializable{
//This does not work. It is always null.
@Inject
private SessionDependnetService sessionDependentService;
public void onLoginEvent(@Observes @OnLogin final Account account) {
//When this methods is invoked
//the sessiondependentservice is always null here.
}
}
在AccountController中,SessionDependentService被正确注入并且不为null,而在AccountObserver,它始终为null。
编辑:使用参数注入的事件仍然会导致null值。
public void onLoginEvent(@Observes @OnLogin final Account account, final SessionDependnetService sessionDependentService) {
//When this methods is invoked
//the sessiondependentservice is always null here.
}
Netbeans正确地将其突出显示为一个注入点。
为什么会出现这种情况?
我使用的是wildfly 8服务器。
我将生产者bean从SessionScoped更改为无状态bean:
@Stateless
public class WebListenerSessionService {
//Use Instance since http session are dynamic.
@Inject
private Instance<HttpSession> httpSession;
@Produces
@Dependent
public SessionDependentService sessionDependentService(){
//use session to lookup existing service or produce a new one.
}
}
尽管这很好,但CDI规范中并没有规定Producer方法必须是会话bean。
报价:
生产者方法必须是默认访问、公共、受保护或私有、非抽象方法托管bean类或会话bean类的。生产者方法可以是静态的,也可以是非静态的-静止的如果bean是会话bean,那么生产者方法必须是EJB或bean类的静态方法
既然@SessionScoped是一个托管bean类,为什么它会注入到观察者bean中而不起作用呢。