Spring Boot提供了兩種格式的配置文件,分別是properties
和 yml
。Spring Boot最大的特點就是自動化配置,如果我們想修改自動化配置的默認值,就可以通過配置文件來指定自己服務器相關的參數。
配置文件集約管理了配置信息,如果把配置參數寫到Java代碼中,維護起來非常不方便,如果使用配置文件,我們可以統一管理,統一修改。我比較推薦使用yml
格式的配置文件,YAML
是專門用來寫配置文件的語言,通常以yml為后綴,它的結構非常清晰,更易於閱讀。
將自定義的配置寫在配置文件中后,如果想要在java代碼中使用配置,這時候就需要讀取配置文件,讀取配置文件的方式有三種,我們挨個介紹一下如果進行讀取!
第一種:使用@Value注解讀取
第一步:在配置文件中增加加入以下配置
config:
name: Java旅途
desc: spring-boot-route
第二部:新建Java類讀取配置信息
@RestController
public class GetValue {
@Value("${config.name}")
private String name;
@Value("${config.desc}")
private String desc;
@GetMapping("getValue")
public String getValue(){
return "name="+name+";desc="+desc;
}
}
@Value注解使用簡單,適合單個參數的注入。
第二種:使用@ConfigurationProperties讀取
@ConfigurationProperties與@Value相比,更加適合讀取數組類型的參數。
1. 獲取單個對象
第一步:在yml文件中新建對象類型的配置信息
configs:
config:
name: Java旅途
desc: spring-boot-route
第二步:新建實體映射配置信息
@Component
@ConfigurationProperties(prefix = "configs.config")
@Data
public class Config {
private String name;
private String desc;
}
第三步:新建類測試是否獲取到參數
@RestController
public class GetConfigurationProperties {
@Autowired
private Config config;
@GetMapping("/getConfig")
public String getConfig(){
return config.getName()+";"+config.getDesc();
}
}
2. 獲取對象集合
第一步:在yml文件中新建數組類型的參數
configs:
config:
- name: Java旅途
desc: spring-boot-route
- name: javatrip
desc: spring-boot-yml
第二步:新建實體映射配置信息
@Component
@ConfigurationProperties(prefix = "configarr")
@Data
public class Configs {
private List<Config> config = new ArrayList<>();
@Data
public static class Config{
private String name;
private String desc;
}
}
第三步:新建測試類獲取參數
@RestController
public class GetConfigurationProperties {
@Autowired
private Configs configs;
@GetMapping("/getConfigs")
public String getConfigs(){
String content = "";
List<Configs.Config> configList = configs.getConfig();
Map<String,Object> map = new HashMap<>();
for (Configs.Config bean : configList){
content += bean.getName()+";"+bean.getDesc()+",";
}
return content;
}
}
除了上面介紹的兩種方式之外,還可以通過Spring Boot上下文的環境變量來讀取配置文件信息,不過上面兩種方式已經完全可以滿足所有需求,這里就不再進行介紹了。
思考與擴展
如果多個配置文件具有相同的配置信息,那么如何讀取特定的配置文件信息呢?
配置文件具有優先級,一般情況下,yml文件的優先級高於properties,這樣就會導致properties的配置信息后加載,最后讀取的時候就會properties的配置信息的優先級會更高。
上面介紹的兩種讀取配置文件的方式可以和另一個注解配合使用,@PropertySource常用的三個屬性,一個是value
用於指定配置文件,另一個是encoding
用於指定編碼,最后一個是factory
,用於指定解析工廠。
這里需要注意一下:@PropertySource默認只會加載properties
格式的文件,也就是我們如果指定了yml
類型的文件是不會生效的,這時候就需要我們重寫解析工廠。
先看看下默認的解析工廠源碼:
public class DefaultPropertySourceFactory implements PropertySourceFactory {
public DefaultPropertySourceFactory() {
}
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
}
}
自定義解析工廠,實現PropertySourceFactory
public class YmlConfigFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String sourceName = name != null ? name : resource.getResource().getFilename();
if (!resource.getResource().exists()) {
return new PropertiesPropertySource(sourceName, new Properties());
} else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
Properties propertiesFromYaml = loadYml(resource);
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
} else {
return super.createPropertySource(name, resource);
}
}
private Properties loadYml(EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
}
}
第一步:新建兩個配置文件,test.yml和test.properties,增加以下配置信息
spring:
value: javatrip123
remark: javatrip123
spring:
value: javatrip123
remark: javatrip123
第二步:指定配置文件映射配置文件內容
@Data
@Configuration
@PropertySource(value = {"classpath:test.yml"},encoding = "gbk")
@ConfigurationProperties(prefix = "spring")
public class Spring {
private String value;
private String remark;
}
第三步:新建類進行測試
@RestController
public class GetSource {
@Autowired
private Spring spring;
@GetMapping("get")
public String getSource(){
return spring.getRemark()+";"+spring.getValue();
}
}
本文示例代碼已上傳至github,點個star
支持一下!
Spring Boot系列教程目錄
spring-boot-route(一)Controller接收參數的幾種方式
spring-boot-route(二)讀取配置文件的幾種方式
spring-boot-route(五)整合swagger生成接口文檔
spring-boot-route(六)整合JApiDocs生成接口文檔
spring-boot-route(七)整合jdbcTemplate操作數據庫
spring-boot-route(八)整合mybatis操作數據庫
spring-boot-route(九)整合JPA操作數據庫
spring-boot-route(十一)數據庫配置信息加密
spring-boot-route(十二)整合redis做為緩存
spring-boot-route(十三)整合RabbitMQ
spring-boot-route(十五)整合RocketMQ
spring-boot-route(十六)使用logback生產日志文件
spring-boot-route(十七)使用aop記錄操作日志
spring-boot-route(十八)spring-boot-adtuator監控應用
spring-boot-route(十九)spring-boot-admin監控服務
spring-boot-route(二十)Spring Task實現簡單定時任務
spring-boot-route(二十一)quartz實現動態定時任務
spring-boot-route(二十二)實現郵件發送功能
spring-boot-route(二十四)分布式session的一致性處理
spring-boot-route(二十五)兩行代碼實現國際化
spring-boot-route(二十六)整合webSocket
這個系列的文章都是工作中頻繁用到的知識,學完這個系列,應付日常開發綽綽有余。如果還想了解其他內容,掃面下方二維碼告訴我,我會進一步完善這個系列的文章!