【问题标题】:CDI scopes in non http application非 http 应用程序中的 CDI 范围
【发布时间】:2016-06-13 10:36:33
【问题描述】:

我正在开发一个没有 http 接口的 Java EE 应用程序:它只使用 MQTT 来发送/接收数据。

我想知道 CDI @SessionScoped@RequestScoped 是否适用于这种情况,或者我必须定义自定义范围来处理客户的请求。

编辑

我尝试了一个简单的应用程序,它在 mqtt 接收回调中注入 @SessionScoped@RequestScoped bean,但我得到一个异常,说我没有活动上下文。

是否可以通过编程方式激活上下文,以便 bean 的生命周期遵循所选范围?

PS:当我发布这个问题时,我并没有懒得做那个简单的测试,但我很想深入研究 CDI 范围理论......而且我仍然......

【问题讨论】:

    标签: jakarta-ee cdi mqtt


    【解决方案1】:

    您可能需要自己创建请求或会话上下文。

    这当然是 CDI 实现和应用程序特定的。

    例如,如果你使用 Weld 并且需要 Request Scope,你可以创建并激活 org.jboss.weld.context.bound.BoundRequestContext。

          /* Inject the BoundRequestContext. */
    
       /* Alternatively, you could look this up from the BeanManager */
    
       @Inject BoundRequestContext requestContext;
    
    
       ...
    
    
       /* Start the request, providing a data store which will last the lifetime of the request */
    
       public void startRequest(Map<String, Object> requestDataStore) {
    
          // Associate the store with the context and activate the context
    
          requestContext.associate(requestDataStore);
    
          requestContext.activate();
    
       }
    
    
       /* End the request, providing the same data store as was used to start the request */
    
       public void endRequest(Map<String, Object> requestDataStore) {
    
          try {
    
             /* Invalidate the request (all bean instances will be scheduled for destruction) */
    
             requestContext.invalidate();
    
             /* Deactivate the request, causing all bean instances to be destroyed (as the context is invalid) */
    
             requestContext.deactivate();
    
          } finally {
    
             /* Ensure that whatever happens we dissociate to prevent any memory leaks */
    
             requestContext.dissociate(requestDataStore);
    
          }
    
       }
    

    你可以在这里找到信息和这个例子https://docs.jboss.org/weld/reference/latest/en-US/html/contexts.html

    也适用于 BoundConversationContext。 会话范围有点困难,您需要在应用程序中提供真正的会话支持才能实现它。

    【讨论】:

    • 感谢您的回答!我阅读了您链接的文档,发现了一些有用的信息。不幸的是,我还没有理解我应该如何使用BoundConversationContext:我应该在我想要一个请求范围的bean中注入上下文并“复制 - 粘贴”你发布的代码吗?我应该从我的代码中调用这些方法还是由容器使用?我应该管理requestDataStore吗?
    • 您需要在访问 Scoped bean 之前关联并激活范围上下文,然后将其停用。这意味着您需要在 bean 之外执行此操作。在您的情况下,例如,如果收到某种偶数或数据,您可以创建对话上下文,并在超时后将其停用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 2012-12-20
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 2012-01-20
    相关资源
    最近更新 更多