January 5, 2017

Configuration in Java EE 6

Background

Dependency Injection has come strong in Java EE 6, which is widely influenced from Spring Framework.

You can use the same pattern to handle configuration.

Code

import java.util.HashMap;
import java.util.Map;

import javax.enterprise.inject.spi.InjectionPoint;

import org.apache.log4j.Logger;

@javax.ejb.Startup
@javax.ejb.Singleton
public class Configuration {

    private final Logger log = Logger.getLogger(Configuration.class);

    private final Map<String, String> configuration = new HashMap<String, String>();

    @javax.annotation.PostConstruct
    public void fetchConfiguration() {
        // load configuration from preferred place and add to map
        configuration.put("se.magnuskkarlsson.examples.lambda.FruitBoundary.noFruits", "999");
    }

    @javax.enterprise.inject.Produces
    public String getString(InjectionPoint point) {
        String fieldClass = point.getMember().getDeclaringClass().getName();
        String fieldName = point.getMember().getName();
        log.info(" >> fieldName : " + fieldClass);
        log.info(" >> fieldName Class : " + fieldName);
        String fieldKey = fieldClass + "." + fieldName;
        String fieldValue = configuration.get(fieldKey);
        log.info("Loaded " + fieldKey + "='" + fieldValue + "'");
        return fieldValue;
    }

    @javax.enterprise.inject.Produces
    public int getInteger(InjectionPoint point) {
        String stringValue = getString(point);
        if (stringValue == null) {
            return 0;
        }
        return Integer.parseInt(stringValue);
    }
}

And to use it

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/fruit")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public class FruitBoundary {

    @Inject
    private int noFruits;

    @GET
    @Path("/{fruitId}")
    public Fruit getById(@PathParam("fruitId") long fruitId) {
        Fruit fruit = new Fruit();
        fruit.setId(fruitId);
        fruit.setName("Apple " + noFruits);
        fruit.setWeight(35);
        return fruit;
    }
}

And finally you need to add and empty WEB-INF/beans.xml to your achieve to make CDI work.

<?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>

No comments: