CDI Eager应用程序作用域bean

时间:2014-04-01 09:18:36

标签: cdi jsf-2.2

由于不推荐使用@ManagedBean(eager = true),如何创建急切的应用程序范围的cdi bean

1 个答案:

答案 0 :(得分:2)

通过使用CDI扩展框架解决了这个问题:

  1. 创建限定符:

    @Qualifier
    @Target(value = {ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER,     ElementType.TYPE})
    @Retention(value = RetentionPolicy.RUNTIME)
    public @interface Eager {
    }
    
  2. 使用observer方法创建扩展实现:

    public class EagerCDIExtension implements Extension {
    
            public void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) {
            beanManager.getBeans(Object.class, new AnnotationLiteral<Eager>() {
            }).parallelStream().filter(bean -> bean.getBeanClass().isAnnotationPresent(ApplicationScoped.class)).forEach(bean -> {
                beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString();
            });
        }
    }
    
  3. 创建:META-INF/services/javax.enterprise.inject.spi.Extension

  4. 在上面的文件中注册扩展implementsatoin类,即:

    pypackage.EagerCDIExtension