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>
Using Java Configuration In this approach, we'll use a Java-based configuration class to configure multiple beans of the same class. Here, @Bean instantiates two beans with ids the same as the method names and registers them within the BeanFactory (Spring container) interface.
Step 1: Define beans by providing some names to them. Step 2: Access specific beans via @Qualifier annotation. @Autowired @Qualifier("krishna") private Employee emp1; @Autowired @Qualifier("ram") private Employee emp2; Find the below working example.
It will throw an error at runtime, as you can not define two Sspring beans of the same class with Singleton Scope in XML. (Very rare) The reference check will return true, as the container maintains one object. Both bean definitions will return the same object, so the memory location would be the same.
The default autowiring is by type, not by name, so when there is more than one bean of the same type, you have to use the @Qualifier annotation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With