为了方便多环境适配,Spring Boot简化了profile功能。
- 默认配置文件application.yaml任何时候都会加载。
- 指定环境配置文件application-{env}.yaml,env通常替代为test,
- 激活指定环境
- 配置文件激活:spring.profiles.active=prod
- 命令行激活:java -jar xxx.jar --spring.profiles.active=prod --person.name=haha(修改配置文件的任意值,命令行优先)
- 默认配置与环境配置同时生效
- 同名配置项,profile配置优先
Profile环境切换功能:
@RestController
public class HelloController {
@Value("${person.name:李四}")
private String name;
@GetMapping("/hello")
public String hello(){
return "Hello"+name;
}
}
默认情况下启动
切换test环境:(在默认配置环境下修改)
当各个配置文件里同时配置了相同配置(server.port)时,先加载默认配置文件,然后以当前设置spring.profiles.active的环境优先
当打包成jar包时,运行时可用这种方法修改环境!
@Profile注解------条件装配功能:
例子:此时激活的是test测试环境(在配置文件中激活),测试@Autowire 引入的是哪位类
Person接口:
public interface Person {
String getName();
Integer getAge();
}
Boss类,实现person接口
@Profile("prod")
@ConfigurationProperties("person")
@Component
@Data
public class Boss implements Person{
private String name;
private Integer age;
}
Worker类
@Profile("test")
@ConfigurationProperties("person")
@Component
@Data
public class Worker implements Person{
private String name;
private Integer age;
}
测试:
还可以用于
@Configuration
public class MyConfig {
@Profile("prod")
@Bean
public Color red(){
return new Color();
}
@Profile("test")
@Bean
public Color green(){
return new Color();
}
}
profile配置分组功能:分组启动相应环境的对应模块功能