JavaEE Contexts and Dependency Injection (CDI) First Steps
How to use Java EE and CDI to execute dependency injections.
Join the DZone community and get the full member experience.
Join For FreeDependency Injections are defined as the ability to inject components into an application in a typesafe way, including the ability to choose at deployment time which implementation of a particular interface to inject.
Loose Coupling
In a regular OO Composition you are including an object into another, the composed object should be instantiated by hand.
The objective here is to decouple these two objects, so the composed object type shouldn’t be a concrete class, It should be an abstract class or an interface, We’re aiming also not to instantiate a new object and assign it to this reference. Someone else (the application server) would search at runtime for a convenient implementation for that reference of type interface then instantiate a new object from it then assign (inject) it to the composing object.
Almost every bean could be injected in CDI plus some other resources that can be injected like EJB Session beans, Persistence contexts and Data sources.
Enabling CDI
To enable CDI in a java web project the WEB-INF directory should contain a file called beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
First Steps in CDI
Suppose we have this interface:
public interface Printer {
void print(String text);
}
We’ll provide an implementation for this interface:
public class SimplePrinter implements Printer{
@Override
public void print(String text) {
System.out.println(text);
}
}
In any class we can make a refrence from Printer and tell the container to look up for an implementation and inject it:
@WebServlet(name = "demo", urlPatterns = "/demo")
public class DemoServlet extends HttpServlet {
@Inject Printer printer;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
printer.print("Helloooooo");
}
}
Multiple Candidates for Injection
If we tries to inject a type using interface, and there are many implementations for this interface
public class FancyPrinter implements Printer{
@Override
public void print(String text) {
System.out.println(" #### " + text + " #### ");
}
}
The container will not succeed to inject the appropriate one, causing an error like this:
CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [Printer] with qualifiers [@Default] at injection point [[BackedAnnotatedField] @Inject demo.DemoServlet.anonymousPrinter]
The solution for this problem is to define the class you want to inject by providing an additional information that would help the container to select the best match. We can simply make a new qualifier annotation to help the container do so.
Our new annotation should be annotated with three anotations:
- @Qualifier To define that this annotation would be a qualifier.
- @Retention(RetentionPolicy.RUNTIME) To define that this annotation would be available at runtime.
- @Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) Qualifier annotation should be applicable to annotate these types: type(class/interface), class filed, method parameter, and method.
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
public @interface Simple {
}
The next step is to annotate our implementation with this new annotation:
@Simple
public class SimplePrinter implements Printer{
@Override
public void print(String text) {
System.out.println(text);
}
}
And inject it using the same annotation:
// = Inject the bean that implements Printer and has an annotation @simple
@Inject @Simple Printer printer;
Another solution is to use the same qualifier annotation but with different values for multiple implemenations.
We can make a new annotation that takes a value like this one:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
public @interface Labeled {
String value();
}
Then rewrite our implementations to use this new annotation:
@Labeled("simple")
public class SimplePrinter implements Printer{
@Override
public void print(String text) {
System.out.println(text);
}
}
@Labeled("fancy")
public class FancyPrinter implements Printer{
@Override
public void print(String text) {
System.out.println(" #### " + text + " #### ");
}
}
Then we can inject both by this way:
//Inject the bean that implements Printer and has an annotation @Labeled that has a value “simple”
@Inject @Labeled("simple") Printer simplePrinter;
//Inject the bean that implements Printer and has an annotation @Labeled that has a value “fancy”
@Inject @Labeled("fancy") Printer fancePrinter;
Produces Method
Sometimes you want to inject a class that you can’t modify its source (that’s imported from an external library or in the java classes).
Other times you want to inject a bean that needs to have some initialization.
The solution for both cases is to make a method that’s responsible for generating the bean:
public class Utils {
@Produces @LoggedIn
public User getLoggedInUser() {
User user = new User();
user.setId(11);
user.setName("Ahmed");
return user;
}
@Produces
public Random getRandom() {
return new Random(System.currentTimeMillis());
}
}
Now you can inject both simply by these lines:
@Inject @LoggedIn User user;
@Inject Random random;
Bean Scopes
The default behavior for injection is called Dependent, means that in every injection point a new instance of the bean would be created and injected.
There’re many scopes for the injection, we can annotate our implementations with these scope annotations to control bean injection
@Dependent in every injection point a new instance would be created.
@RequestScoped The same bean would be injected as we still in the scope of the same request.
@SessionScoped The same bean would be injected for every session, thus means that a bean for every user would be created and injected.
@ApplicationScoped Only one bean would be created and injected for all users for all injection points (=Singleton).
@ConversationScoped A custom scope that its lifetime is bigger than @RequestScoped and less than @SessionScopedIt’s used in wizard pages to reach the same bean instance across multiple pages.
Published at DZone with permission of Hany Ahmed. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments