application.properties的简单用法及编码格式

2022-11-23  本文已影响0人  entro

application.properties的简单用法及编码格式问题

配置文件有三种:xml properties yml

1. 加载顺序

ConfigFileApplicationListener(spring 2.4-3.0)中的DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/"指定了默认的配置文件加载目录.

2. 属性使用

单个字段使用
class A{
        @Value("${environment}")
        private String environment;
}
对象整体使用,
@ConfigurationProperties(prefix = "cn.tocute.env")
class EnvBean{}
@EnableConfigurationProperties({EnvBean.class})
@SpringBootApplication
public class App {}

3. application.properties 文件编码类型为ISO8859-1

application.properties一般不支持中文,因为其默认编码在jdk11以下为ISO8859-1,如果要只用中文值,则一般需要转换成形如\u1212的ascii码(unicode-escapes).

因为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++]);
    }
上一篇 下一篇

猜你喜欢

热点阅读