第二章 Spring Cloud部分基础

2018-11-27  本文已影响13人  靈08_1024

spring cloud配置优先级

启动命令行参数 > 远程配置源属性 > application.yml > bootstrap.yml
“引导”属性例外。例如当bootstrap.yml中存在spring.config.location属性时,所有的属性都以bootstrap.yml的为准,且application.yml是无法覆盖的。而在没有spring.config.location属性时,其他属性都会被覆盖。(此处的其他属性包括远程config配置地址。spring别的本地引导配置的方式未测试)

自动载入外部属性

第一步 - 导入jar包:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

第二步 - 编写属性类和配置:
下面的@Componet@ConfigurationProperties必须有,而且@ConfigurationProperties注解必须要写前缀(默认值也是前缀)。所有的属性,会先去application.yml中查找,没有再去@PropertySource注解对应的文件中查找。而且@PropertySource指定的文件,除application.yml(支持yml语法)以外,其他都只支持键值对形式,即sms.retry=3的形式。

@Component
@ConfigurationProperties(prefix = "sms")
@PropertySource("classpath:a.yml")
public class SMS {
    private int retry;
    private String smsTitle;
    private List<String> types = new ArrayList<>();

//  ...getter and  setter
//   ...toString
}

我以在application.yml中的示例为例(在非spring默认文件需以a=1的形式编写):

sms:
  retry: 4
  sms-title: 我是谁
  types:
    - sms
    - message

第三步 - 使用

@Autowired
    private SMS sms;

    @RequestMapping("name")
    public String name() {
        //记得重写toString,在此处可以直接看属性值
        System.out.println(sms);
        return sms.toString();
    }

输出结果:SMS{retry=3, smsTitle='我是谁', types=[sms, message]}。


上一篇 下一篇

猜你喜欢

热点阅读