springboot与springcloud配置文件说明
springboot支持的配置文件为以下三种
- application.yaml
- application.yml
- application.properties
三种文件的加载优先级为,后缀为:yaml > yml > properties,所以优先级越大的配置会被优先级小的配置文件覆盖,同时springboot 不支持bootstrap为前缀的配置文件。如果有多环境配置,springboot也支持加载以下形式的配置文件:(假设环境为dev)
- application-dev.yaml
- application-dev.yml
- application-dev.properties
application.* > application-dev.*。后缀的加载跟上面一样。
springcloud 支持的配置文件为以下六种(因为springcloud是基于springboot的所以,springboot的配置文件,springcloud也可以读取)
- bootstrap.yaml
- bootstrap.yml
- bootstrap.properties
- application.yaml
- application.yml
- application.properties
如果有多环境还支持以下的配置文件 (同样假设环境为dev)
- bootstrap-dev.yaml
- bootstrap-dev.yml
- bootstrap-dev.properties
- application-dev.yaml
- application-dev.yml
- application-dev.properties
springcloud的配置文件的加载顺序与springboot的同理。 对应的前缀加载顺序为,bootstrap.* > bootstrap-dev.* > application.* > application-dev.* 对应的后缀加载顺序为,yaml > yml > properties
Spring Boot 中读取配置文件有以下 5 种方法:
使用 @Value 读取配置文件。
@Configuration public class Config { @Value("${spring.profiles.active}") private String active; @PostConstruct public void test(){ System.out.println(active); } }
使用 @ConfigurationProperties 读取配置文件。
@Data @Component @ConfigurationProperties(prefix = "pre") public class PropertyConfigProperties { private String name; private Integer age; }
使用 Environment 读取配置文件。
@Component public class EnvironmentProperties implements EnvironmentAware { @Override public void setEnvironment(Environment environment) { System.out.println(environment.getProperty("pre.name")); } }
使用 @PropertySource 指定读取配置文件,需要与@Value()配合使用。真正读取值还是@Value()注解读取。 使用原生方式读取配置文件。(此种方式如果是读取yaml或者yml文件会有问题,无法读取出对应的层级关系)例:
pre: name: aaa
读取之后会变成两个参数:pre 和 name,这是因为Properties::load方法是按照行进行读取的,一次读取8kb的数据
@Component public class ReadFileProperties implements InitializingBean { @Override public void afterPropertiesSet() { Properties properties = new Properties(); try { properties.load(this.getClass().getClassLoader().getResourceAsStream("application-dev.yaml")); }catch (IOException ioException){ System.out.println(ioException); } System.out.println(properties.getProperty("pre.name")); } }