Learning CDI (Contexts and Dependency Injection) Part 2

This is second part of CDI discussion. If u r not visited, Please visit first part,

           Its annotation, its helps to create our qualifier annotation. We already seen if we have more than one implementation of particular interface then we can't inject, because ambiguity issues are arise. so we need to define own qualifiers and marked the annotation with that qualifier. When inject we need to mention the qualifier.

For Example

We have one interface and two implementation

Hello Interface

HelloImplOne Implementation

HelloImplTwo Implementation

 In Injection  Point (i.e where u inject the class, i.e where u use @inject key word) if u try to inject using interface like this u get AmbiguousResolutionException.

but we can still use like this
@javax.inject.Inject HelloImplOne hello;
@javax.inject.Inject HelloImplTwo hello;

so we need use qualifier

we can create own qulaifier like any class

@Qualifier - is annotation to represent that we r creating custom qualifier. while deploying the container
check that class contain qualifier annotation is present. If its present container treat  class as qualifier.

@Retention(RUNTIME) - its like decision maker. this annotation decides that our annotation is present in runtime or compile time.
possible Values are (RUNTIME, CLASS, SOURCE)
RUNTIME - annotation is stored in class file and while running JVM can see the annotation is reflection API
CLASS - annotaion is stored in class file but its not visible in JVM. Its mainly used by deployment time (ie. we can inform to container)
SOURCE - this annotation is not stored in class file. its only used for inform some info to compiler. (Ex: @Override its inform to compiler this method is going to override.).

@Target({METHOD, FIELD, PARAMETER, TYPE}) - What are the places we can use our annotation. here we can use to any method, fields, parameter declaration's and any class and interface see all possible values hereso finally we create 'Hi' qualifier from above code. we use this qualifier to solve the ambiguous problem.take any class implementation from above code (here i take HelloImplTwo) and add our new qualifier 'Hi' with '@' symbol(it represent annotation)

HelloImplTwo Implementation

thats its. now in injection point
if you using like this
then Class HelloImplOne is injected.

if you using like this

then Class HelloImplTwo is injected.

Please see the Third part here

see the Screen cast 

Please see the Third part here

Comments are welcomed