How to instantiate more CDI beans for one class?

时光总嘲笑我的痴心妄想 提交于 2019-12-19 08:12:36

问题


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?

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.....

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

Spring Example:

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

回答1:


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;

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

@Inject
@HooQualifier
private MyBean hoo;

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;
}

and then producer method:

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

then simply calling:

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

will result in MyBean instance with someProperty equal to 11.



来源:https://stackoverflow.com/questions/25153624/how-to-instantiate-more-cdi-beans-for-one-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!