DI / CDI – Basics

Introduction (DI/CDI Basics)

First of all, I would assume there is a bit of confusion to this, but the truth of the matter is, they are just the same – the difference is that usage and its purpose.

DI (Dependency Injection) is the general term  – this feature is basically the one doing the bean discovery and bean wiring process on any application. Its not just you use it in your application, you can also use it in your unit tests and mocks. Of course, there are a lot of DI frameworks out there, you have: Guice, Seam, Spring (Seam and Spring extended the DI scheme and made their own), EJB 3.x and CDI itself.

CDI on the other hand, combines all this technology and introduce a lifecycle to the components – this allowed unification of DI technologies to making development of new features straight forward and mostly doable; you can combine Seams lifecycle mappings with Spring MVC with JPA as its persistence layer – these technologies were all created separately yet with CDI, application developers can combine them to create and development JEE application.

I will need to break down the topics as I would definitely bore everyone with words and letters here so:

  1. DI / CDI Basics
  2. Basic Injection
  3. Qualifiers, Scope
  4. DI / CDI Advance

I will be creating separate posts for each!

Lets Begin!

SPI (Service Programming Interface)

It also has this so called SPI – apparently a feature set along with API, but has a different purpose entirely.

  • The API is the description of classes/interfaces/methods/… that you call and use to achieve a goal.
  • The SPI is the description of classes/interfaces/methods/… that you extend and implement to achieve a goal.

With SPI, you can actually extend the JEE6 to create a different framework of your own, showcasing portability, and extensibility. (But I’ll dive into that later).

Why CDI for JEE6?

CDI has been around in JEE5 (J2EE) and has been a major success. A lot of new development benefits from its approach that ultimately simplifies the overall development process. Several reasons why CDI was improved in JEE6.

  • JEE5 do support resource injection, but it still lacks a general purpose dependency – it only supports @EJB, @PersistenceContext, @PersistenceUnit, @Resources) – of course this is with the exception of Spring that introduce different annotations for managing bean lifecycle
  • Non-type based injection (and weak)  – String name and XML injection is really fragile. Improving type-based injetcion enables better tooling in general.

Terminology

CDI – Context and Dependency Injection

Weld

  • JSR 299 reference implementation – reference implementation is the SPI used to etxend a JSR specific implementation.
  • Provides extended CDI support for Servlet Container.
  • CDI enhancements for extension writers.
  • Maven Archetypes for CDI and Java EE (I love maven!).

CDI Theme: Loose Coupling and Strong Typed

Loose coupling simply means objects is loosely independent to the objects that uses or currently using them. CDI introduces new features for decoupling such as qualifiers, enhances interceptors, decorators, message producer, consumer and its underlying events mechanisms. Will dive further in to each example on the advance topic of CDI.

Strong Typing - simply means that strict declaration of beans by letting the container create and map specific names to objects. This eliminates the need to do string based naming of beans, casting almost not needed since the casting is done by the container (by taking advantage of qualifiers).

Bean (What is it?)

There are technically many form of beans, you have: JSF Bean, EJB Bean, Spring, Seam, Guice CDI, Entity Beans, etc – but ultimately, beans are just POJOs that has special definition – definition that was defined by the Managed Bean 1.0 – specification made in Java EE6. What does this mean is that any POJOs can be any type of bean, as long as it complies with the specification standards – further simplifying the declaration and development process. The container does the work for managing the POJOs and will add support for it by giving / introducing common basic services such as:

  • Lifecycle Management (@PostConstruct, @PreDestory)
  • Injection of a resource (@Resource)
  • Interceptor (@Interceptors, @ArounInvoke)
@javax.annotation.ManagedBean
public class MyPojo {

@Resource   // Resource injection
private Datasource ds;

@PostConstruct  // Life-cycle
private void init() {
   ....
}  
@Interceptors(LoggingInterceptor.class)
   public void myMethod() {...}
}

With this in mind, what about EJBs, RESTs and CDI beans?

  • EJB bean service – managed bean, with the common services (above) and support for Transaction, security, thread safety and persistence.
  • REST bean service – managed bean with HTTP support
  • CDI bean – managed bean with lifecycle supports:
    • Auto discovery
    • Qualifiers
    • Scope
    • EL
    • Interceptors and Decorators
    • Alternative bean (by Qualifiers at runtime)

To put it into perspective, Manage Bean is ultimately an SPI that was extended for specific use. EJBs, Rest, Entity beans are all Managed Beans – but with additional services from the container. Thus, if you define a POJO with a @Stateless or @Stateful annotation, the container automatically detects that its an EJB bean and it needs container specific support like transactions, security, thread safety, extensions etc.

package mypackage;
import javax.ejb.Stateless;

@Stateless
public class GreetingBean {
  public String greet(String name){
      return "Hello " + name;
   }
}

A simple POJO class turned into a Stateless bean with just a flick of finger (actually typed in) that resulted to that one liner @Stateless code. Unlike how EJB was defined on the priori 3.x (such a pain).

Download the sample (above) from here: Click me

Automatic Bean Discovery

The CDI container is the one responsible for how the beans are discovered, but how does it do it?

  1. It first scan the classpath that contains both application and container archives.
    1. It tries to scan through the classpath and see what POJOs are tag for discovery – that is, Managed Bean. You can think of it that it puts in a pool and can readily available when another Managed Bean calls it thru injection (more on that on next blog topic)
  2. Then it detects presence of beans.xml (or any context xml file definition).
    1. For Spring fans, this is much like an applicationContext.xml (at least thats the convention, but loose) – you pass that xml on the contextConfiguration listener (thru parameter) and Spring CDI Container will automatically tag objects (beans) in it for discovery – of course you need to define scanning mechanisms (component-scan).

Ultimately, DI / CDI was introduce to simplify the development process, unify the technologies and overall to produce a more robust, extendible application. Letting all the container do the work in terms of tagging the common services of the bean makes the developer task easier and more over avoiding pitfalls as a result of previous frameworks. SPI – is really the definition of improvement here, allowing the actually JEE6 framework to be extendible creates a more dynamic nature – business application architects can now design their own framework and conventions. Put more business specific designs or annotations for their own rules and give the robustness and flexibility that is always required for enterprise application.

Next Topic: Basic Injection – I don’t want to put everything in one post, so I’ll leave it up to you to absorb first and check the sample I created. From here on now, I’ll tackle more on the examples of DI and CDI.

 

Reference: DI / CDI – Basics from our JCG partner Alvin Reyes at the Alvin “Jay” Reyes Blog blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


− seven = 1



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close