为了方便多环境适配,Spring Boot简化了profile功能。

application.properties
server.port=8080
spring.profiles.active=prod
application-prod.properties
project.env=prod
application-test.properties
project.env=test
@Controller
public class HelloController {
@Value("${project.env}")
private String env;
@ResponseBody
@GetMapping("/test")
public String test1(){
return "env="+env;
}
}

把web项目打包为jar包, 在命令行中启动
java -jar springboot-test2-0.0.1-SNAPSHOT.jar --spring.profiles.active=test


命令中还可以修改配置文件中的任意属性
java -jar springboot-test2-0.0.1-SNAPSHOT.jar --spring.profiles.active=test --server.port=8081 --project.env=cmd-test


@Profile可写在类上或者方法上, 当为指定环境时该类或者方法才生效
MyConfig
@Configuration
public class MyConfig {
private String env;
@Profile("test") //当环境是test时才生效
@Bean
public Color red() {
Red red = new Red();
red.setName("red");
return red;
}
@Profile("prod") //当环境是prod时才生效
@Bean
public Color bule() {
Blue blue = new Blue();
blue.setName("blue");
return blue;
}
}
HelloController
```java
@Controller
public class HelloController {
@Value("${project.env}")
private String env;
@Autowired
private Color color;
@ResponseBody
@GetMapping("/test")
public String test1(){
System.out.println("env="+env);
return "color="+color.getName();
}
}
Color
```java
public interface Color {
String getName();
}
Blue
@Data
public class Blue implements Color{
private String name;
}
Red
@Data
public class Red implements Color {
private String name;
}

application.properties
server.port=8080
spring.profiles.active=test
application-prod.properties
project.env=prod
application-test.properties
project.env=test


配置文件可以分组, 然后可以整合导入使用

application.properties
server.port=8080
spring.profiles.active=production
spring.profiles.group.production[0]=prod1
spring.profiles.group.production[1]=prod2
application-prod1.properties
color.name=red
application-prod2.properties
color.size=10
HelloController
@Controller
public class HelloController {
@Autowired
private Red red;
@ResponseBody
@GetMapping("/test")
public Red test1(){
return red;
}
}
Red
@Data
@Component
@ConfigurationProperties(prefix = "color")
public class Red {
private String name;
private Integer size;
}

外部配置源(优先级由低到高)
配置文件查找位置
配置文件加载顺序:
指定环境优先,外部优先,后面的可以覆盖前面的同名配置项。