注意:类似的问题已经在三年前问过,当时是 EE 6,请参阅 how to instantiate more then one CDI/Weld bean for one class? EE 7 有什么变化吗?
在 Spring 中,可以通过在 xml conf 中定义相应的 bean 来实例化任何类。也可以使用不同的参数为一个类实例化多个bean.....
是否可以在 CDI 中实现,我的意思是创建一个实例而不创建另一个类?
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,如下所示:
@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。
关于java - 如何为一个类实例化更多的CDI bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25153624/