Search code examples
javacdi

CDI. Using @Specializes


I have a question about using @Specialization. As prescribed by the Java EE 6 or 7 tutorials if I declare my bean by giving it @Specializes annotation that it ' ll completely replace bean, which extends my bean. E.g.

    public interface I {}
    @Default @Q
    public class A implements I {}
    @Specializes
    public class SpecA extends A {}
    ////
    a) @Inject I a;
    b) @Inject @Q I b;

Is it enough for that SpecA will be injected to fields 'a' and 'b'? I tried to run this example on glassfish 4.0 and it didn't worked.

I have read strange sentences in tutorials: 'Usually, a bean marked with the @Specializes annotation is also an alternative and is declared as an alternative in the beans.xml file. ' I don't understand what should I do to do make it work as prescribed in tutorials? Do I need add annotation @Alternative and add this class to beans.xml? Or Do I need add my bean to beans.xml?


Solution

  • To answer your questions

    Do I need add annotation @Alternative and add this class to beans.xml?

    Yes

    Do I need add my bean to beans.xml?

    No. Above will do

    Giving you more context :

    @Specializes is more or less meant to specialize an @Alternative bean.

    @Specializes comes handy when the @Alternative bean is meant to replace

    • a bean/implementation that is annotated with one or more qualifiers and
    • the injection points are using the one/more qualifiers.

    Case 1 : You have one bean/implementation (lets call BeanA) with no qualifiers. In this case you don't need @Specializes, you will have to

    1. Create a @Alternative bean (let's call AltBean) that you want to use as a replacement for BeanA
    2. List AltBean in beans.xml as alternative

    Case 2 : You have one bean/implementation (in your case A) with one or more qualifiers. In this case you have to

    1. Create a @Alternative and @Specializes bean (SpecA) that you want to use as a replacement for A
    2. Make SpecA extend A
    3. List SpecA in beans.xml as alternative

    Yours is Case 2.