【问题标题】:SessionScoped cdi observer with @Inject for producer bean带有 @Inject 的 SessionScoped cdi 观察者用于生产者 bean
【发布时间】:2024-01-13 21:20:01
【问题描述】:

这是我目前的情况:

@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。 p>

编辑: 使用参数注入的事件仍然会产生空值。

 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 服务器。

【问题讨论】:

    标签: java jakarta-ee cdi wildfly-8


    【解决方案1】:

    我将生产者 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 规范中也没有规定生产者方法必须是会话 bean。

    引用:

    生产者方法必须是默认访问、公共、受保护或私有、非抽象方法 托管 bean 类或会话 bean 类。生产者方法可以是静态的或非 静止的。如果 bean 是会话 bean,则生产者方法必须是 EJB 或 bean 类的静态方法。

    既然@SessionScoped 是一个托管 bean 类,为什么注入观察者 bean 不起作用。

    【讨论】:

      最近更新 更多