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

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

配置文件有三种:xml properties yml

1. 加载顺序

  • 距离最近的先加载,后加载/config下的,距离远最后再加,后加载的覆盖先加载的属性。
  • .YML比.properties优先,//todo 这里试验下加载顺序,是否加载一个不加载另一个类型的文件
  • bean类或者主入口上面加@PropertySource可以指定加载配置文件,其值最先加载,被后加载的覆盖

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;
}
对象整体使用,
  • 1.gradle引入 'org.springframework.boot:spring-boot-configuration-processor'
  • 2.在properties文件中定义好配置字段合集
  • 3..新建一个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一般不支持中文,因为其默认编码在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++]);
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容