我的项目使用 JSF2.0 和 CDI。对于一页,我希望我的支持 bean 与页面的生命周期相匹配。 @ViewScoped 似乎非常合适,但它不是 CDI 的一部分,然后使我们的解决方案不一致。那么我的下一个选择是 CDI @ConversationScoped。在我看来,标记对话边界的唯一方法是通过conversation.begin 和conversation.end 的程序方式(我使用了Seam 2.x,您可以使用注释来标记对话边界)。我的页面位于具有全局导航的通用布局中,这意味着可以通过“无限”方式离开我的页面。我如何确保以用户可能选择的方式结束对话(例如,单击完全不受我的支持 bean 控制的全局导航选项)?我希望该解决方案不会将代码传播到其他模块;如果这是不可避免的,我希望它可以以跨领域的方式 (AOP) 实现。

最佳答案

这可以通过自定义 ConfigurableNavigationHandler 来实现。

  • 实现一个 JSF NavigationHandler
     public class NavigationHandlerTest extends ConfigurableNavigationHandler {
    
     private NavigationHandlerTest concreteHandler;
    
     public NavigationHandlerTest(NavigationHandler concreteHandler) {
          this.concreteHandler = concreteHandler;
     }
    
    
     @Override
     public void handleNavigation(FacesContext context, String fromAction, String outcome)
     {
        //here, check where navigation is coming from and based on that, retrieve the CDI bean and kill the conversation
         if(fromAction.equals("someAction"){
         BeanManager theBeanManager = getBeanManager(context);
         Bean bean = theBeanManager.getBeans("yourCDIBean").iterator().next()
         CreationalContext ctx = theBeanManager.createCreationalContext(bean);
         MyBeanType o = theBeanManager.getReference(bean, bean.getClass(), ctx); //retrieve the bean from the manager by name. You're guaranteed to retrieve only one of the same name;
         o.getConversation.end(); //end the conversation from the bean reference
          }
    
         //proceed with normal navigation
         concreteHandler.handleNavigation(context, fromAction, outcome);
    
     }
    
     //This method provides access to the cdi bean manager. You need it to be able to
     //gain access to the cdi bean and from that to the injected conversation instance
     public BeanManager getBeanManager(FacesContext facesContext){
       BeanManager cdiBeanManager = (BeanManager)((ServletContext) facesContext.getExternalContext().getContext()).getAttribute("javax.enterprise.inject.spi.BeanManager");
        return cdiBeanManager;
     }
    
    
       }
    
  • 在 faces-config.xml 中注册您的自定义导航处理程序
     <application>
         <navigation-handler>com.foo.bar.NavigationHandlerTest</navigation-handler>
     </application>
    

  • 这种方法是集中的、微创的

    关于jakarta-ee - 如何干净地结束 CDI @ConversationScoped,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15394148/

    10-13 03:36