Spring boot allows to add profile-specific properties files by using application-{myProfileName}.properties pattern.
To load a specific profile property file we can use command line option -Dspring.profiles.active=myProfileName.
The default file application.properties can still be used by not using any -Dspring.profile.active option or by using -Dspring.profiles.active=default. The default properties file can be named as application-default.properties as well.
The properties specified in default application.properties are overridden by the profile-specific file properties.
Example
The default property file
src/main/resources/application.propertiesapp.window.width=500
app.window.height=400
Profile specific files
src/main/resources/application-dev.propertiesapp.window.height=300
src/main/resources/application-prod.propertiesapp.window.width=600
app.window.height=700
Example Application
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class ClientBean {
@Value("${app.window.width}")
private int width;
@Value("${app.window.height}")
private int height;
@PostConstruct
private void postConstruct() {
System.out.printf("width= %s, height= %s%n", width, height);
}
}
package com.logicbig.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExampleMain {
public static void main(String[] args) {
SpringApplication.run(ExampleMain.class, args);
}
}
Running
$ mvn spring-boot:run
width= 500, height= 400
$ mvn -Dspring.profiles.active=dev spring-boot:run
width= 500, height= 300
$ mvn -Dspring.profiles.active=prod spring-boot:run
width= 600, height= 700
Example ProjectDependencies and Technologies Used: - Spring Boot 2.0.5.RELEASE
Corresponding Spring Version 5.0.9.RELEASE - spring-boot-starter : Core starter, including auto-configuration support, logging and YAML.
- JDK 1.8
- Maven 3.5.4
|