Excitements, confusions and frustrations

Knowledge without action is wastefulness and action without knowledge is foolishness. - Al-Ghazali

Configuring environment values with Spring boot

Posted at — May 28, 2018

At our company Java is one of primary programming languages. And this means that Spring Framework is widely used.
We didn’t have much problem with Spring except that is wasn’t easy to configure for different environments. However, after introduction of Environment abstraction into Spring, configuration based on environment became easier.

Environment specific configuration with Spring Boot

But, it wasn’t as simple as other web framework such as Ruby on Rails, Laravel until Spring Boot came out. Spring Boot provides flexible and easy to understand way to configure our (web) application.

For example, if we have following in our application.properties file in src/main/resources:

application.admin.secret = '5b0b8f1245e7d'

it can be assigned to a class property with @Value annotation.

import org.springframework.beans.factory.annotation.Value;

public class Authentication {
	@Value("${application.admin.secret}")
	private String adminSecret;
}

Now value of adminSecret is set to '5b0b8f1245e7d'.

Or even better, we can use YAML file for configuration. So using application.yml instead of application.properties with following content will give us the same result.

application:
	admin:
		secret: '5b0b8f1245e7d'

Beside this, Spring Boot is great for configuring environment based configuration. Let’s consider another case where we want to use different secret key for development environment. Then we can add that key as in sample below.

application:
	admin:
		secret: '5b0b8f1245e7d'
---
spring:
	profiles: dev
application:
	admin:
		secret: 'development-key-45e7d'

Now profile can be activated by adding active profile as java commandline property.

java -jar -Dspring.profiles.active=dev

But what would we do if configuration for different environment is too many?
Luckily Spring Boot has Profile-specific properties. We can add our environment configuration files into application-dev.yml file, and when -Dspring.profiles.active=dev is provided, Spring Boot will load configuration from that file, and overwrite the ones from application.yml. This is useful when we want to allow custom environment, or separate configuration from source code.

Configuration with Tomcat

For web applications, setting active profile can be delegated if we are using Tomcat. All we have to do is add -Dspring.profiles.active=dev/prod/integration to the CATALINA_OPTS in catalina.sh file. For example,

CATALINA_OPTS="$CATALINA_OPTS -Dspring.profiles.active=dev"

Then during deployment, only releasing war file is sufficient, we won’t have to worry about changing environment programatically or setting it manually in a file.

comments powered by Disqus