jakarta-ee - 如何干净地结束 CDI @ConversationScoped

标签 jakarta-ee jsf-2 cdi

我的项目正在使用 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/

    相关文章:

    jsf - CDI bean 构造函数和@PostConstruct 多次调用

    java - 带有自定义注释的 Quarkus CDI

    eclipse - JSF 2.0 应用程序找不到资源

    java - 带有列标题的 Primefaces 订单列表

    java - JBoss 中的 EJB 特化

    java - JAX-WS复杂对象

    javascript - f :ajax and jquery's `$(document).ajaxStart` dont work together?

    javascript - 使用Java Servlet下载动态文件

    java - 从 java web 应用程序启动很长的后台进程的最佳方法是什么?

    java - 如何在远程 ejb 查找期间设置超时?