vendredi 21 mars 2014

Injection de configuration avec CDI

Il suffit de créer une factory pour CDI et une annotation (tiré du blog http://codebias.blogspot.fr/2013/04/environment-configuration-property.html) .

Création de l'annotation

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.enterprise.util.Nonbinding;
import javax.inject.Qualifier;
 
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Configuration {
    @Nonbinding
    String value() default "";
}

Création de la factory

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
 
@ApplicationScoped
public class ConfigurationFactory {
 
    private static final String ENVIRONMENT_NAME_KEY = "environment.name";
    private static final String DEFAULT_PROPS_FILENAME = "environment.properties";
    private static final String PROPS_FILENAME_FORMAT = "environment_%s.properties";
    private Properties environmentProps;
 
    @PostConstruct
    public void initEnvironmentProps() throws IOException {
        environmentProps = new Properties();
        String propsFilename = DEFAULT_PROPS_FILENAME;
        String environmentName = System.getProperty(ENVIRONMENT_NAME_KEY);
        if (environmentName != null) {
            propsFilename = String.format(PROPS_FILENAME_FORMAT, environmentName);
        }
        try(InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propsFilename)){
            if (inputStream == null) {
                throw new FileNotFoundException("Properties file for environment " + environmentName + " not found in the classpath.");
            }
            environmentProps.load(inputStream);
        }
       
    }
 
    @Produces
    @Configuration
    public String getConfigValue(InjectionPoint ip) {
        Configuration config = ip.getAnnotated().getAnnotation(Configuration.class);
        String configKey = config.value();
        if (configKey.isEmpty()) {
            throw new IllegalArgumentException("Properties value key is required.");
        }
        return environmentProps.getProperty(configKey);
    }
}

Comment on l'appel ? 

//Usage
@Inject
@Configuration("url")
private String testUrl;
//...