1

是否可以将@SessionScopedbean 用作自定义范围的 Context 中的字段?

我正在使用 CDI 编写自定义范围(“ScreenScoped”),因此它与 CDI 的行为大致相同@ViewScoped(我这样做是因为后者不兼容 WebSphere)。到目前为止,我的范围就像@ApplicationScoped这样。我想使用我的@SessionScoped NavigationHandler类(每次用户单击链接或按钮时调用)来确定我的 ScreenScoped 生命周期何时结束。但是,当我尝试使用@Injected 字段时,我确实遇到了错误。

public class ScreenContext
    implements Context
{
    @Inject
    private NavigationHandler navigationHandler;
    ...
}

由于以下原因出现 NullPointerException @Inject

16:55:07,492 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost/127.0.0.1:8443-10) Error Rendering View[/page/hello.xhtml]: javax.el.ELException: /page/hello.xhtml @24,58 visible="#{helloController.popupshowed}": java.lang.NullPointerException

...

Caused by: java.lang.NullPointerException
    at com.mypackage.scope.screenscope.ScreenContext.get(ScreenContext.java:38) [myproject.jar:]

第 38 行是我第一次调用注入字段:

System.out.println("Navigation is used: " + navigationHandler.getUserId());
4

1 回答 1

2

你不能在Context. 您需要使用BeanManager来访问NavigationHandlerbean。

您的上下文是通过AfterBeanDiscoveryCDI 生命周期的 CDI 扩展观察事件注册的。在这里,您将 传递BeanManager给 context :

public void afterBeanDiscovery (@Observes final AfterBeanDiscovery event, final BeanManager beanManager)
{
    event.addContext(new ScreenContext(beanManager));
}

然后在您的ScreenContext实现中,您可以使用以下方法获取NavigationHandlerbean(myMethod如下所示)BeanManager

public class ScreenContext implements Context
{

   private final BeanManager m_beanManager;

   public ScreenContext(final BeanManager p_BeanManager)
   {
      m_beanManager = p_BeanManager;
   }

   public void myMethod()
   {
      NavigationHandler NavigationHandlerBean = getNavigationHandler();
      ...
      ...
   }

   private NavigationHandler getNavigationHandler()
   {
      final Set<Bean<?>> beans = m_beanManager.getBeans(NavigationHandler.class);
      final Bean<?> bean = m_beanManager.resolve(beans);

      return (NavigationHandler) m_beanManager.getReference(bean, NavigationHandler.class, m_beanManager.createCreationalContext(bean));
   }
于 2017-02-11T17:24:50.217 回答