Profiles and env variables

Profiles example

application.properties.yml

server:  
  port: 8080  
spring:  
  config: 
	import:
		- "application.properties-dev.yml"
		- "application.properties-qa.yml"
		- "application.properties-prod.yml"
  datasource:  
    url: jdbc:h2:mem:testdb  
    driverClassName: org.h2.Driver  
    username: sa  
    password: ''  
  h2:  
    console:  
      enabled: true  
  jpa:  
    database-platform: org.hibernate.dialect.H2Dialect  
    hibernate:  
      ddl-auto: update  
    show-sql: true  
build:  
  version: 1

application.properties-dev.yml

server:  
  port: 8081  
spring:
	config:
		activate:
			on-profile: "dev"

application.properties-qa.yml

server:  
  port: 8082   
spring:
	config:
		activate:
			on-profile: "qa"

application.properties-prod.yml

server:  
  port: 8083  
spring:
	config:
		activate:
			on-profile: "prod"

Then, when running your application, specify the active profile using the command line:

java -jar your-application.jar --spring.profiles.active=dev

Alternatively, you can set the active profiles inside the properties file

spring.profiles.active=dev

Notice we are using yaml format but this will be the same with .properties format as well

If you have properties that are common across all profiles and you want to avoid duplication, you can include those properties in the main application.properties file. When Spring Boot loads profile-specific properties, it will merge them with the properties from the main file. If there are conflicting property keys, the profile-specific values will override the main values.

Env variables

Notice in the last example how we use the command line argument --spring.profiles.active=dev to override a property, you can do this to override any property, also you can use env variables, command line arguments or jvm arguments

If you have a property defined in your application.properties or application.yml file, you can override it using an environment variable with the same name. For example, if you have server.port in your properties file, you can override it using an environment variable named SERVER_PORT.

Here's a quick example:

Suppose you have the following property in your application.properties:

server.port=8080

You can override it using an environment variable:

export SERVER_PORT=9090

In case the same property is defined in multiple places, Spring Boot uses a priority order that is designed to allow sensible overriding of values, properties are considered in the the following order:

  1. Command line arguments.
  2. JNDI attributes from java:comp/env.
  3. Java System properties (System.getProperties()).
  4. OS environment variables.
  5. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
  6. Default application,properties file