application.properties的簡單用法及編碼格式問題
配置文件有三種:xml properties yml
1. 加載順序
- 距離最近的先加載仿便,后加載/config下的体啰,距離遠(yuǎn)最后再加,后加載的覆蓋先加載的屬性探越。
- .YML比.properties優(yōu)先狡赐,//todo 這里試驗(yàn)下加載順序,是否加載一個(gè)不加載另一個(gè)類型的文件
- bean類或者主入口上面加@PropertySource可以指定加載配置文件钦幔,其值最先加載枕屉,被后加載的覆蓋
ConfigFileApplicationListener
(spring 2.4-3.0)中的DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/"
指定了默認(rèn)的配置文件加載目錄.
2. 屬性使用
單個(gè)字段使用
class A{
@Value("${environment}")
private String environment;
}
對(duì)象整體使用,
- 1.gradle引入 'org.springframework.boot:spring-boot-configuration-processor'
- 2.在properties文件中定義好配置字段合集
- 3..新建一個(gè)bean類,定義好字段和其setter,getter鲤氢,在該類上加上注解
@ConfigurationProperties(prefix = "cn.tocute.env")
class EnvBean{}
- 4.在主類入口加上注解@EnableConfigurationProperties,并指明加載的bean類搀擂。
@EnableConfigurationProperties({EnvBean.class})
@SpringBootApplication
public class App {}
3. application.properties 文件編碼類型為ISO8859-1
application.properties
一般不支持中文西潘,因?yàn)槠淠J(rèn)編碼在jdk11以下為ISO8859-1
,如果要只用中文值,則一般需要轉(zhuǎn)換成形如\u1212
的ascii碼(unicode-escapes
).
因?yàn)?code>utf-8在英文字符兼容ISO8859-1
哨颂,所以utf-8
編碼的配置文件如果全是英文字符喷市,也可以被正確讀取.
讀取application.properties
的類是:
org.springframework.boot.env.PropertiesPropertySourceLoader.loadProperties()
org.springframework.core.io.support.PropertiesLoaderUtils.loadProperties(org.springframework.core.io.Resource)
org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(java.util.Properties, org.springframework.core.io.Resource)
java.util.Properties.load(java.io.InputStream)
在jdk8中大約447行這里,使用ISO8859-1
編碼讀取配置文件
if (inStream != null) {
//The line below is equivalent to calling a
//ISO8859-1 decoder.
c = (char) (0xff & inByteBuf[inOff++]);
}