1. Problems
In software development, there are often development environments, test environments, pre-release environments, and production environments. Generally, these environments are configured differently. Manually changing the configuration is troublesome and error-prone. How to manage the configuration parameters of different environments? spring-boot + maven can solve the problem of configuring different parameters independently in different environments.
2. Multi-environment configuration
The configuration yml file names for different environments are different:
- application-dev.yml (development environment)
- application-test.yml (test environment)
- application-uat.yml (pre-release)
- application-pro.yml (production environment)
eg:
Application-dev.yml configuration example:
info: build: name: ${project.artifactId} groupId: ${project.groupId} artifactId: ${project.artifactId} version: ${project.version} server: port: 8081 endpoints: enabled: true sensitive: false data: test: envName: dev envconfig: 127.0.0.1:8081
application.yml
spring:
profiles:
active: dev
If you want to switch between different environments, you only need to modify spring.profiles.active.
Read configuration parameters:
@Setter @Getter @NoArgsConstructor @AllArgsConstructor @Component @ConfigurationProperties(prefix = "data.test") public class DataConfig { private String envName; private String envconfig; }
Verify environment parameters:
@Api("home controller") @RestController public class HomeController { @Autowired private DataConfig dataConfig; @RequestMapping("/env") @ApiOperation("env") public Object testEnv() { return dataConfig; } }
3. Setting the environment
1. Set spring.profiles.active when starting the jar package
java -jar muti-env-config.jar --spring.profiles.active=test
2. Set the environment when maven is packaged (set the pro environment)
clean package -DskipTests -Ppro
Pro environment example: