Sunday, June 4, 2017

JavaEE: Dependency Injection by Using Producer Methods

Context and Dependency Injection (CDI) is one of Java EE features that helps developers make it easy to use enterprise beans.  CDI enables objects to have their dependencies provided to them automatically instead of creating a new object explicitly in the objects.

On this page, we will talk about Java EE producer method, which is one way of creating an injectable object.  This example is continuously built on the TomEE server.  Initial setting and a pom project configuration on the TomEE is explained on previous posts.

First of all, CDI uses an optional deployment descriptor named beans.xml. The beans.xml can be an empty file but should exist under the META-INF directory.  In my pom project with auto created default directory structure, the META-INF directory should be created under a src/main/resources directory.



Basic content of the bean.xml is shown here.  This is for CDI 1.1.  The bean-discovery-mode is a new element in CDI 1.1 and it informs the CDI to discover all beans, none, or only annotated ones.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">
</beans>

Producer Method
A producer method is a method that generates an object that can be injected.  It enables an application to customize how CDI managed beans are created.  It provides a way to inject objects that are not beans, objects whose values may vary at runtime, and objects that require custom initialization.

This is a class that creates an injectable Logger object.  I use a Logger object that comes with Java, but you can use any other Logger object.  The Producer method is annotated with a @Prodecues annotation.  This is it.  Simple!

import java.util.logging.Logger;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

public class LogProducer {
   @Produces
   public Logger createLogger(InjectionPoint injectionPoint) { 
      return Logger.getLogger( injectionPoint.getMember().getDeclaringClass().getName() );
   }
}

I will show how to inject this Logger object on a next post, but it is simple.  You can declare a Logger object variable with an @Inject annotation.

@Inject
private Logger logger;

 

No comments:

Post a Comment

Java 9: Flow - Reactive Programming

Programming world has always been changed fast enough and many programming / design paradigms have been introduced such as object oriented p...