Spring初始化读取配置文件与placeholder使用
- 实现功能
在spring context配置文件中使用占位符${key}读取本地配置文件中的配置key=value
- org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
这个类负责在应用启动时候读取配置文件中的配置并解析placeholders
配置文件位置
- 指定目录
- 指定 classpath:
- 指定绝对路径 file:
systemPropertiesModeName
PropertyPlaceholderConfigurer的属性systemPropertiesModeName指定了解析placeholder时针对系统属性的策略,默认为SYSTEM_PROPERTIES_MODE_FALLBACK
Spring provides three modes as follows:
SYSTEM_PROPERTIES_MODE_FALLBACK: if a placeholder could not be resolved by the specified properties files, Spring will try to resolve it with a system property
SYSTEM_PROPERTIES_MODE_OVERRIDE: In this mode, Spring will resolve the placeholders to system properties first. If a system property does exist, its value will override the value in the properties file.
SYSTEM_PROPERTIES_MODE_NEVER: Spring will not take system properties into consideration when resolving the placeholders.
- 异常
当找不到配置文件或无法解析placeholder时会抛出相应异常,以下两个属性控制是否ignore,一般不会置为true
ignoreUnresolvablePlaceholders:无法解析直接用placeholder的名字,没人这样用的吧
ignoreResourceNotFound:忽略资源文件找不到异常