PropertySourcesPlaceholderConfigurer读取配置文件的坑

时间:2024-04-07 22:32:54

spring中读取属性配置文件一般会使用PropertySourcesPlaceholderConfigurer,成功读取后,可以将配置文件中的属性在XML中使用${xxx}的写法引入。

在做Junit单元测试时,启动报错:

PropertySourcesPlaceholderConfigurer读取配置文件的坑

无法cms.master.url这个属性,这说明property-placeholder并未成功读取到该属性所在的配置文件。检查下配置文件:

PropertySourcesPlaceholderConfigurer读取配置文件的坑

xml中使用的是这个引入的properties文件,但没有读取到文件中配置的属性。说明这句没有生效

往上继续查找,发现已经有这样的配置了,问题出在这里,

PropertySourcesPlaceholderConfigurer读取配置文件的坑

修改成在这里进行扫描

PropertySourcesPlaceholderConfigurer读取配置文件的坑

 

注意:

Spring容器采用反射扫描的发现机制,在探测到Spring容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描(Spring 3.1已经使用PropertySourcesPlaceholderConfigurer替代PropertyPlaceholderConfigurer了)。 

而这个基于命名空间的配置,其实内部就是创建一个PropertyPlaceholderConfigurer Bean而已。换句话说,即Spring容器仅允许最多定义一个PropertyPlaceholderConfigurer(或),其余的会被Spring忽略掉。所以当上面已经创建了一个 PropertyPlaceholderConfigurer时,后面再去读取时是不会生效的。