青海西寧網(wǎng)站建設(shè)公司電腦編程培訓(xùn)學(xué)校
前言
Spring Boot 官方提供了兩種常用的配置文件格式,分別是properties
、YML
格式。相比于properties
來說,YML
更加年輕,層級也是更加分明。
1. properties格式簡介
常見的一種配置文件格式,Spring中也是用這種格式,語法結(jié)構(gòu)很簡單,結(jié)構(gòu)為:key=value。具體如下:
userinfo.name=myjszl
userinfo.age=25
userinfo.active=true
userinfo.created-date=2018/03/31 16:54:30
userinfo.map.k1=v1
userinfo.map.k2=v2
上述配置文件中對應(yīng)的實體類如下:
@Data
@ToString
public class UserInfo {private String name;private Integer age;private Boolean active;private Map<String,Object> map;private Date createdDate;private List<String> hobbies;
}
2.YML格式簡介
以空格的縮進程度來控制層級關(guān)系??崭竦膫€數(shù)并不重要,只要左邊空格對齊則視為同一個層級。注意不能用tab代替空格。且大小寫敏感。支持字面值,對象,數(shù)組三種數(shù)據(jù)結(jié)構(gòu),也支持復(fù)合結(jié)構(gòu)。
字面值:字符串,布爾類型,數(shù)值,日期。字符串默認(rèn)不加引號,單引號會轉(zhuǎn)義特殊字符。日期格式支持yyyy/MM/dd HH:mm:ss
對象:由鍵值對組成,形如 key:(空格)value 的數(shù)據(jù)組成。冒號后面的空格是必須要有的,每組鍵值對占用一行,且縮進的程度要一致,也可以使用行內(nèi)寫法:{k1: v1, …kn: vn}
數(shù)組:由形如 -(空格)value 的數(shù)據(jù)組成。短橫線后面的空格是必須要有的,每組數(shù)據(jù)占用一行,且縮進的程度要一致,也可以使用行內(nèi)寫法:[1,2,…n]
復(fù)合結(jié)構(gòu):上面三種數(shù)據(jù)結(jié)構(gòu)任意組合
如何使用
在src/resources文件夾下創(chuàng)建一個application.yml文件。支持的類型主要有字符串,帶特殊字符的字符串,布爾類型,數(shù)值,集合,行內(nèi)集合,行內(nèi)對象,集合對象這幾種常用的數(shù)據(jù)格式。
具體的示例如下:
userinfo:age: 25name: myjszlactive: truecreated-date: 2018/03/31 16:54:30map: {k1: v1,k2: v2}hobbies:- one- two- three-
上述配置文件對應(yīng)的實體類如下:
@Data
@ToString
public class UserInfo {private String name;private Integer age;private Boolean active;private Map<String,Object> map;private Date createdDate;private List<String> hobbies;
}
如何從配置文件取值?
一切的配置都是為了取值,Spring Boot也是提供了幾種取值的方式,下面一一介紹。
@ConfigurationProperties
這個注解用于從配置文件中取值,支持復(fù)雜的數(shù)據(jù)類型,但是不支持SPEL表達式。
該注解中有一個屬性prefix,用于指定獲配置的前綴,畢竟配置文件中的屬性很多,也有很多重名的,必須用一個前綴來區(qū)分下。
該注解可以標(biāo)注在類上也可以標(biāo)注在方法上,這也注定了它有兩種獲取值的方式。
- 標(biāo)注在實體類上
這種方式用于從實體類上取值,并且賦值到對應(yīng)的屬性。使用如下:
/*** @Component :注入到IOC容器中* @ConfigurationProperties:從配置文件中讀取文件*/
@Component
@ConfigurationProperties(prefix = "userinfo")
@Data
@ToString
public class UserInfo {private String name;private Integer age;private Boolean active;private Map<String,Object> map;private Date createdDate;private List<String> hobbies;
}
標(biāo)注在配置類中的方法上
標(biāo)注在配置類上的方法上,同樣是從配置文件中取值賦值到返回值的屬性中。使用如下:
/*** @Bean : 將返回的結(jié)果注入到IOC容器中* @ConfigurationProperties :從配置文件中取值* @return*/@ConfigurationProperties(prefix = "userinfo")@Beanpublic UserInfo userInfo(){return new UserInfo();}
總結(jié)
@ConfigurationProperties
注解能夠很輕松的從配置文件中取值,優(yōu)點如下:
支持批量的注入屬性,只需要指定一個前綴prefix支持復(fù)雜的數(shù)據(jù)類型,比如List、Map對屬性名匹配的要求較低,比如user-name,user_name,userName,USER_NAME都可以取值支持JAVA的JSR303數(shù)據(jù)校驗
注意:@ConfigurationProperties
這個注解僅僅是支持從Spring Boot的默認(rèn)配置文件中取值,比如application.properties、application.yml。
@Value
@Value這個注解估計很熟悉了,Spring中從屬性取值的注解,支持SPEL表達式,不支持復(fù)雜的數(shù)據(jù)類型,比如List。使用如下:
@Value("${userinfo.name}")private String UserName;
如何從自定義配置文件中取值?
Spring Boot在啟動的時候會自動加載application.xxx和bootsrap.xxx,但是為了區(qū)分,有時候需要自定義一個配置文件,那么如何從自定義的配置文件中取值呢?此時就需要配合@PropertySource這個注解使用了。
只需要在配置類上標(biāo)注@PropertySource并指定你自定義的配置文件即可完成。如下:
@SpringBootApplication
@PropertySource(value = {"classpath:custom.properties"})
public class DemoApplication {}
value屬性是一個數(shù)組,可以指定多個配置文件同時引入。
@PropertySource默認(rèn)加載xxx.properties類型的配置文件,不能加載YML格式的配置文件,怎么破???
如何加載自定義YML格式的配置文件?
@PropertySource注解有一個屬性factory,默認(rèn)值是PropertySourceFactory.class,這個就是用來加載properties格式的配置文件,我們可以自定義一個用來加載YML格式的配置文件,如下:
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;import java.io.IOException;
import java.util.Properties;public class YmlConfigFactory extends DefaultPropertySourceFactory {@Overridepublic 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();}}
此時只需要將factory屬性指定為YmlConfigFactory即可,如下:
@SpringBootApplication
@PropertySource(value = {"classpath:custom.yml"},factory = YmlConfigFactory.class)
public class DemoApplication {
總結(jié)
@PropertySource指定加載自定義的配置文件,默認(rèn)只能加載properties格式,但是可以指定factory屬性來加載YML格式的配置文件。