<context:property-placeholder>标签提供了一种优雅的外在化参数配置的方式,不过该标签在Spring配置文件中只能存在一份!!!

众所周知,Spring容器是采用反射扫描的发现机制,通过标签的命名空间实例化实例,当Spring探测到容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderCVonfigurer的Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描,即只能存在一个实例!

这是对spring配置文件中context标签的表述,由此可知这个标签全局只能存在一个。如果项目的spring配置文件多个,且每个配置文件中都有引入外部properties文件,则使用此方式:

如果location中有多个文件: 
classpath:db.properties,classpath:default.properties,classpath:default3.properties,classpath:default2.properties 
将依次加载,值得注意的是如果后一个文件中有和前面某一个文件中属性名是相同的,最终取的值是后加载的值 
举例来说: 
default.properties文件中有个属性名userId,其对应的值为-1 
default2.properties文件中也有一个属性名userId,其对应的值为-2 
default3.properties文件中特有一个属性名userId,其对于那个的值为-3

default.properties文件先加载,此时userId的值为-1,当default3.properties文件加载时将更新原来的值,此时userId的值为-3,同理,最后加载default2.properties文件,所以userId最终值为-2 
所以需要避免不同属性文件中的属性名称重名

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐