MyArchiBook

Archive for June 2014

CDI – Lifecycle Management by Container

with 3 comments

We know that, CDI Managed Beans are contextual. Their lifecycle management is done by the container. One of its main advantages is type-safe dependency injection.

But how does it do it?
In the below code, during application initialization process, the container checks for Type-Safe Resolution for News bean annotated with @Inject and then instantiates it.

TYPE-SAFE RESOLUTION:

Here the container checks ,

  • if the bean type is equal to the required type(type: News here) at the injection point in Consumer Bean class.
  • if the qualifier of bean is equal to the required qualifier at the injection point.
  • (If no qualifier specified , then default qualifier is @Default)


@Stateless
public class News {
  public String getLatestNews(){
    return "FIFA 2014 WorldCup";
  }
}

@Stateless
@Path(value = "consumer")
public class Consumer {

  @Inject
  private News news;

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("latestNews")
  public String tweetLatestNews(){
    return news.getLatestNews();
  }
}

Any mismatch will result in unsatisfied or ambiguous dependency problem.

CREATION AND DESTRUCTION BY CONTAINER:

 

Reference:

http://www.oracle.com/technetwork/articles/java/cdi-javaee-bien-225152.html
http://docs.jboss.org/weld/reference/latest/en-US/html/injection.html
http://docs.jboss.org/cdi/spec/1.0/html/contexts.html
http://docs.jboss.org/cdi/spec/1.0/html/injectionelresolution.html#ambigdependencies

Advertisements