Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to instantiate more than one CDI/Weld bean for one class?

In Spring it was possible to instantiate any class by defining the corresponding bean in xml conf. It was also possible to instantiate more then one bean for the same class with different parameters.....

Are the such features in CDI as well, namely is it possible to create different instances of the same class with different initialization parameters?

Is it also possible to create a bean without changing the class....I mean without adding annotation?

ADDED

Let me make an example.

<bean id="someBean1" class="org.mm.MyBean">
    <property name="x" value="xx"/>
    <property name="y" value="yy"/>
    <property name="z" value="zz"/>       
</bean>
<bean id="someBean2" class="org.mm.MyBean">
    <property name="x" value="other value"/>
    <property name="y" value="yy2"/>
    <property name="z" value="zz2"/>       
</bean>

How can instantiate two instances of the same class and initialize them with different field values?

like image 703
qwertz1123 Avatar asked Feb 23 '10 14:02

qwertz1123


2 Answers

Two options as far as I can see:

  • Without further knowledge of your usecase, I assume that you either want to provide some alternative implementation for (mock-) testing or configuration issues (say another PaymentProvider for a OrderService). This is supported by the spec itself, have a look at @Alternative here (and don't repeat my initial mistake and forget to activate alternatives in beans.xml)

  • To get a Spring-style XML-configuration, you can use Seam 3 Config, which provides XML-configuration just as described. BTW, this has been a part of JSR 299, but has been removed from the spec for whatever reason.

like image 161
Jan Groth Avatar answered Sep 28 '22 08:09

Jan Groth


there are a few ways to do that.

E.g. use @New

private @Inject @New YourBean yb; private @Inject @New YourBean yb2;

This forces the container to create a new instance, regardless what Scope the bean originally had.

Another way would be to simply define YourBean as being @Dependent scoped (which is btw (currently) the default if a class is not annotated at all).

like image 26
struberg Avatar answered Sep 28 '22 08:09

struberg