64.高级特性-Profile环境切换

为了方便多环境适配,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条件装配功能
@Data
@Component
@ConfigurationProperties("person")//在配置文件中配置
public class Person{
    private String name;
    private Integer age;
}

application.properties

person: 
  name: lun
  age: 8

public interface Person {

   String getName();
   Integer getAge();

}

@Profile("test")//加载application-test.yaml里的
@Component
@ConfigurationProperties("person")
@Data
public class Worker implements Person {

    private String name;
    private Integer age;
}

@Profile(value = {"prod","default"})//加载application-prod.yaml里的
@Component
@ConfigurationProperties("person")
@Data
public class Boss implements Person {

    private String name;
    private Integer age;
}

application-test.yaml

person:
  name: test-张三

server:
  port: 7000
1
2
3
4
5
application-prod.yaml

person:
  name: prod-张三

server:
  port: 8000

application.properties

# 激活prod配置文件
spring.profiles.active=prod
1
2
@Autowired
private Person person;

@GetMapping("/")
public String hello(){
    //激活了prod,则返回Boss;激活了test,则返回Worker
    return person.getClass().toString();
}

@Profile还可以修饰在方法上:

class Color {
}

@Configuration
public class MyConfig {

    @Profile("prod")
    @Bean
    public Color red(){
        return new Color();
    }

    @Profile("test")
    @Bean
    public Color green(){
        return new Color();
    }
}

可以激活一组:

spring.profiles.active=production

spring.profiles.group.production[0]=proddb
spring.profiles.group.production[1]=prodmq

 

posted @ 2022-08-09 16:12  随遇而安==  阅读(40)  评论(0编辑  收藏  举报