Skip to content

Instantly share code, notes, and snippets.

@nazartm
Last active December 16, 2015 05:09
Show Gist options
  • Save nazartm/5382355 to your computer and use it in GitHub Desktop.
Save nazartm/5382355 to your computer and use it in GitHub Desktop.
Environment configuration property injection using CDI
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 "";
}
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);
}
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);
}
}
//Usage
@Inject
@Configuration("url")
private String testUrl;
//...
@jriffotoro
Copy link

An injection point has type InjectionPoint and qualifier @default but bean declares not @dependent scope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment