如何为一个类实例化更多的CDI bean? [英] How to instantiate more CDI beans for one class?

查看:71
本文介绍了如何为一个类实例化更多的CDI bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:三年前在EE 6时代已经问过类似的问题,请参见如何实例化一个类的一个CDI / Weld bean呢? EE中有什么变化吗? 7

Note: The similar question has been already asked three years ago, in time of EE 6, see how to instantiate more then one CDI/Weld bean for one class? Has something changed in EE 7?

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

In Spring there is possible to instantiate any class by defining the corresponding bean in xml conf. It is also possible to instantiate more beans for one class with different parameters.....

是否可以在CDI中实现,我是说要创建一个实例而不创建另一个类?

Is it possible to do it in CDI, I mean to create an instance without creating another class?

Spring示例:

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


推荐答案

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

I would create qualifiers FooQualifier,HooQualifier and Producer for MyBean, something like this:

@ApplicationScoped
public class MyBeanProducer {

    @Produces
    @FooQualifier
    public MyBean fooProducer() {
        return new MyBean(42);
    }

    @Produces
    @HooQualifier
    public MyBean hooProducer() {
        return new MyBean(666);
    }
}

然后,如果您在某个地方这样做:

Then if you somewhere do:

    @Inject
    @FooQualifier
    private MyBean foo;

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

You will have MyBean instance with foo.getSomeProperty() equal to 42 and if you do:

@Inject
@HooQualifier
private MyBean hoo;

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

you will have MyBean instance with foo.getSomeProperty() equal to 666.

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

Another possibility is to have one configurable qualifier:

@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。

will result in MyBean instance with someProperty equal to 11.

这篇关于如何为一个类实例化更多的CDI bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆