Java EE6 CDI, Named Components and Qualifiers

One of the biggest promises java EE6 made, was to ease the use of dependency injection. They did, using CDI. CDI, which stands for Contexts and Dependency Injection for Java EE, offers a base set to apply dependency injection in your enterprise application.

Before CDI, EJB 3 also introduced dependency injection, but this was a bit basic. You could inject an EJB (statefull or stateless) into another EJB or Servlet (if you container supported this). Offcourse not every application needs EJB’s, that is why CDI is gaining so much popularity.

To start, I have made this example. There is a Payment interface, and 2 implementations. A cash payment and a visa payment.

I want to be able to choose witch type of payment I inject, still using the same interface:

public interface Payment {
    void pay(BigDecimal amount);
}

Here are the 2 implementations:

public class CashPaymentImpl implements Payment {
 
    private static final Logger LOGGER = Logger.getLogger(CashPaymentImpl.class.toString());
 
    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} cash", amount.toString());
    }
}
public class VisaPaymentImpl implements Payment {
 
    private static final Logger LOGGER = Logger.getLogger(VisaPaymentImpl.class.toString());
 
    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} with visa", amount.toString());
    }
}

To inject the interface we use the @Inject annotation. The annotation does basically what it says. It injects a component, that is available in your application.

@Inject private Payment payment;

Off course, you saw this coming from a mile away, this won’t work. The container has 2 implementations of our Payment interface, so he does not know which one to inject.

Unsatisfied dependencies for type [Payment] with qualifiers [@Default] at injection point [[field] @Inject private be.styledideas.blog.qualifier.web.PaymentBackingAction.payment]

So we need some sort of qualifier to point out what implementation we want. CDI offers the @Named Annotation, allowing you to give a name to an implementation.

@Named("cash")
public class CashPaymentImpl implements Payment {
 
    private static final Logger LOGGER = Logger.getLogger(CashPaymentImpl.class.toString());
 
    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} cash", amount.toString());
    }
}
@Named("visa")
public class VisaPaymentImpl implements Payment {
 
    private static final Logger LOGGER = Logger.getLogger(VisaPaymentImpl.class.toString());
 
    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} with visa", amount.toString());
    }
}

When we now change our injection code, we can specify which implementation we need.

@Inject private @Named("visa") Payment payment;

This works, but the flexibility is limited. When we want to rename our @Named parameter, we have to change it on everyplace where it is used. There is also no refactoring support.

There is a beter alternative using Custom made annotations using the @Qualifier annotation. Let us change the code a little bit.

First of all, we create new Annotation types.

@java.lang.annotation.Documented
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@javax.inject.Qualifier
public @interface CashPayment {
}
@java.lang.annotation.Documented
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@javax.inject.Qualifier
public @interface VisaPayment {
}

The @Qualifier annotation that is added to the annotation, makes this annotation discoverable by the container. We can now simply add these annotations to our implementations.

@CashPayment
public class CashPaymentImpl implements Payment {
 
    private static final Logger LOGGER = Logger.getLogger(CashPaymentImpl.class.toString());
 
    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} cash", amount.toString());
    }
}
@VisaPayment
public class VisaPaymentImpl implements Payment {
 
    private static final Logger LOGGER = Logger.getLogger(VisaPaymentImpl.class.toString());
 
    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} with visa", amount.toString());
    }
}

The only thing we now need to do, is change our injection code to

@Inject private @VisaPayment Payment payment;

When we now change something to our qualifier, we have nice compiler and refactoring support. This also adds extra flexibilty for API or Domain-specific language design.

Reference: Java EE6 CDI, Named Components and Qualifiersfrom our JCG partner Jelle Victoor at Styled Ideas Blog.

Related Articles :
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


1 × = one



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books