Is the @Qualifier annotation needed at all? Can’t we just inject an instance of particular type? It seems like a little extra work, since we have to create annotation type for each implementing class. To show what I mean, here is the example below:
@Documented
@Retention(RUNTIME)
@Qualifier
public @interface AppleQ { }
@Documented
@Retention(RUNTIME)
@Qualifier
public @interface CheeseQ { }
public interface Eatable { }
@AppleQ
public class Apple implements Eatable { }
@CheeseQ
public class Cheese implements Eatable { }
public class Breakfast {
@Inject @AppleQ Eatable somethingToEat;
}
vs
public interface Eatable { }
public class Apple implements Eatable { }
public class Cheese implements Eatable { }
public class Breakfast {
@Inject Apple somethingToEat;
}
You are (kind of) right, your example works without qualifiers. But its rather that your example is a bit misleading than that you don’t need qualifiers.
In general, you will need qualifiers whenever you have have more than one managed bean of a certain type eligible for injection. This is not the case in your example, but would easily be if you wrote your code like this:
(This gives you the flexibility to change your implementation later, for the same reason as you normally write
List list = new ArrayList())You will not need qualifiers if you have just one managed bean of a certain type eligible for injection.
More serious examples where you want to use qualifiers would look like this:
Imagine you want have a class
Localein your system. Using different qualifiers (together with different producer methods) would allow you to write code like this:To summarize: You need qualifiers if and only if you have more than one bean of a type. This makes qualifiers redundant for the overwhelming majority of you beans – but you will certainly need them.
All this and much more is best read here.