spring 使用 context:property-placeholder 加载 多个 properties

一般使用PropertyPlaceholderConfigurer来替换占位符,例如:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
      <value>classpath:com/foo/strategy.properties</value>
  </property>
  <property name="properties">
      <value>custom.strategy.class=com.foo.DefaultStrategy</value>
  </property>
</bean>

spring 2.5之后,可以使用

<context:property-placeholder location="classpath:com/foo/jdbc.properties"/>

其本质是注册了一个PropertyPlaceholderConfigurer(3.1之前)或者是PropertySourcesPlaceholderConfigurer(3.1之后)

Tip:


PropertyPlaceholderConfigurer内置的功能非常丰富,如果它未找到${xxx}中定义的xxx键,它还会去JVM系统属性(System.getProperty())和环境变量(System.getenv())中寻找。通过启用systemPropertiesMode和searchSystemEnvironment属性,开发者能够控制这一行为。

而PropertySourcesPlaceholderConfigurer在此基础上会和Environment and PropertySource配合更好。

另外需要注意以下几点

1、在PropertyPlaceholderBeanDefinitionParser的父类中shouldGenerateId返回true,即默认会为每一个bean生成一个唯一的名字; 如果使用了两个<context:property-placeholder则注册了两个PropertySourcesPlaceholderConfigurer Bean;所以不是覆盖(而且bean如果同名是后边的bean定义覆盖前边的); 
2、PropertySourcesPlaceholderConfigurer本质是一个BeanFactoryPostProcessor,spring实施时如果发现这个bean实现了Ordered,则按照顺序执行;默认无序; 
3、此时如果给<context:property-placeholder加order属性,则会反应出顺序,值越小优先级越高即越早执行; 
比如 
   <context:property-placeholder order="0" location="classpath:dbconfig.properties"/>  
   <context:property-placeholder order="1" location="classpath*:conf/conf_a.properties"/>  
   <context:property-placeholder order="2" location="classpath*:conf/conf_b.properties"/> 
此时会先扫描order='1' 的,如果没有扫描order='2'的 
4、默认情况下ignore-unresolvable;即如果没找到的情况是否抛出异常。默认false:即抛出异常; 
<context:property-placeholder location="classpath*:conf/conf_a.properties" ignore-unresolvable="false"/>

posted on   陈惟鲜的博客  阅读(3263)  评论(0编辑  收藏  举报

编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示