【问题标题】:How to instantiate more CDI beans for one class?如何为一个类实例化更多的 CDI bean?
【发布时间】:2014-08-06 17:44:46
【问题描述】:

注意:类似的问题已经在三年前问过,在 EE 6 的时候,请参阅 how to instantiate more then one CDI/Weld bean for one class?EE 7 有什么变化吗?

在 Spring 中,可以通过在 xml conf 中定义相应的 bean 来实例化任何类。也可以用不同的参数为一个类实例化更多的bean.....

是否可以在 CDI 中做到,我的意思是创建一个实例而不创建另一个类?

春季示例:

<bean id="foo" class="MyBean">
    <property name="someProperty" value="42"/>
</bean>
<bean id="hoo" class="MyBean">
    <property name="someProperty" value="666"/>      
</bean>

【问题讨论】:

    标签: java cdi java-ee-7


    【解决方案1】:

    我会为 MyBean 创建限定符 FooQualifier、HooQualifier 和 Producer,如下所示:

    @ApplicationScoped
    public class MyBeanProducer {
    
        @Produces
        @FooQualifier
        public MyBean fooProducer() {
            return new MyBean(42);
        }
    
        @Produces
        @HooQualifier
        public MyBean hooProducer() {
            return new MyBean(666);
        }
    }
    

    如果你在某个地方这样做:

        @Inject
        @FooQualifier
        private MyBean foo;
    

    您将拥有 foo.getSomeProperty() 等于 42 的 MyBean 实例,如果这样做:

    @Inject
    @HooQualifier
    private MyBean hoo;
    

    您将拥有 foo.getSomeProperty() 等于 666 的 MyBean 实例。

    另一种可能性是有一个可配置的限定符:

    @Target( { TYPE, METHOD, PARAMETER, FIELD })
    @Retention(RUNTIME)
    @Documented
    @Qualifier
    public @interface ConfigurableQualifier {
    
        @Nonbinding
        int value() default 0;
    }
    

    然后是生产者方法:

    @Produces
    @ConfigurableQualifier
    public MyBean configurableProducer(InjectionPoint ip){
        int somePropertyValue = ip.getAnnotated().getAnnotation(ConfigurableQualifier.class).value();
        return new MyBean(somePropertyValue);
    }
    

    然后简单地调用:

    @Inject
    @ConfigurableQualifier(value = 11)
    private MyBean configurableBean;
    

    将导致 MyBean 实例的 someProperty 等于 11。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2011-05-31
    • 2013-03-05
    • 2017-09-17
    • 2016-08-05
    相关资源
    最近更新 更多