Marcos J.C Kichel
Marcos J.C Kichel

Reputation: 7219

How to make CDI decide the implementation to use according to generic type of the bean

This is, briefly, my architecture:

enter image description here

What I want to achieve is to make CDI inject the correct implementation of the BO inside the Controller, and the right implementation of the DAO inside the BO accourding to the generic type of the Controller.

How can I achieve that?

Upvotes: 1

Views: 185

Answers (1)

Marcos J.C Kichel
Marcos J.C Kichel

Reputation: 7219

I solved the problem using an javax.enterprise.inject.Instance object to encapsulate my bo's and dao's. This way:

@Inject
private Instance<CrudBO<T>> bo;

public CrudBO<T> getBo() {
    return bo.get();
}

Just to make things clear, CrudBO is the interface that GenericCrudBO implements, so, knowing that by default the GenericCrudBO is annotated with @Default, I annotated the specialized classes with @Alternative:

@Alternative
public class SpecializedCrudBO extends GenericCrudBO<SpecificClass>{
}

I also declared the alternatives BO's and DAO's in beans.xml:

<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

    <alternatives>
        <class>com.kichel.marcos.business.SpecializedCrudBO</class>
        ...
    </alternatives>

</beans>

And now CDI can handle my generic java beans at runtime, this is very good also because I dont have to create tons of boilerplate classes.

Upvotes: 1

Related Questions