SpringBoot高级特性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环境切换功能

@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配置分组功能:分组启动相应环境的对应模块功能

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值