Skip to content

Application configuration

mekor-dev edited this page Sep 29, 2020 · 1 revision

To add configuration properties that are environment dependent, I use maven profiles and the Properties Maven Plugin

Doc: https://www.mojohaus.org/properties-maven-plugin

Maven Profiles and properties

To add a property for a given environment, we use maven profiles as followed:

<profile>
	<id>profileName</id>

	<properties>
		<property.name>value</property.name>
	</properties>
</profile>

We can then build the project with a given profile

mvn clean compile package -PprofileName

Properties Maven Plugin

This plugin writes, during the maven build, the properties from the pom.xml to a specified file (here, app-config.properties).

<plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>properties-maven-plugin</artifactId>
	<version>1.0.0</version>
	<executions>
		<execution>
			<phase>generate-resources</phase>
			<goals>
				<goal>write-project-properties</goal>
			</goals>
			<configuration>
				<outputFile>${project.build.outputDirectory}/app-config.properties</outputFile>
			</configuration>
		</execution>
	</executions>
</plugin>

For our previous exemple, the plugin will write:

property.name=value

AppConfig.java

The AppConfig class read the app-config.properties file and store the properties in its attribut. As this class is ApplicationScoped, you can access it in the whole application.

@Inject
@InjectableResource(location = "app-config.properties")
private Properties configProps;

public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
	log.debug("Entering init()");

	// Setting properties
	property = configProps.getProperty("property.name");

	// Logging properties
	log.info("-------------------------------------------------");
	log.info("AppConfig controller has inited with following values:");
	log.info("Property: {}", property);
}
@Inject
private AppConfig appConfig;

public void getProperty(){
	return appConfig.getProperty();
}

Clone this wiki locally