Spring加载properties配置文件使用PropertyPlaceholderConfigurer还是使用PropertySourcesPlaceholderConfigurer

多模块的项目中,不建议直接在@Value中初始化默认值,各个模块的properties配置文件建议使用PropertyPlaceholderConfigurer加载,或者在主模块中定义一个PropertySourcesPlaceholderConfigurer,加载你需要的所有模块中的properties属性。

  1. 使用PropertyPlaceholderConfigurer配置:

    主模块引入先引入<import resource="classpath:spring/spring-api-log.xml"/>后引入<import resource="classpath:spring/spring-shiro-client.xml"/>,内容分别如下

    spring-api-log.xml内容:
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	<property name="locations">
    		<list>
    			<value>classpath:api-access-log.properties</value>
    		</list>
    	</property>
    	<property name="ignoreUnresolvablePlaceholders" value="true" />
    </bean>
    
    spring-shiro-client.xml内容:
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    	<property name="locations">  
    		<list>  
    			<value>classpath:shiro-client.properties</value>  
    		</list>  
    	</property>  
    	<property name="ignoreUnresolvablePlaceholders" value="true" />   
    </bean>
    

    代码如下:

    @Value("${api.access.log.prefix:com.commons}")
    private String logPrefix;
    
    @Value("${shiro.platform:2}")
    private String shiroPlatform;
    

    两个属性都给了默认值,由于先引入的是spring-api-log.xml,因此logPrefix的值会引用加载的api-access-log.properties配置文件中的值,而shiroPlatform使用默认值2,并不会加载shiro-client.properties配置文件中的值。如果两个属性都没有默认值,两个属性都会初始化为配置文件中的值。

  2. 使用propertySourcesPlaceholderConfigurer配置:引入多个模块的配置文件时,只会加载第一个配置文件中配置的properties

    主模块引入先引入<import resource="classpath:spring/spring-api-log.xml"/>后引入<import resource="classpath:spring/spring-shiro-client.xml"/>,内容如上,但是beanclass换成<bean id="propertySourcesPlaceholderConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"></bean>

    无论两个属性有没有默认值,由于后引入的是spring-shiro-client.xml,因此shiroPlatform的值都会从shiro-client.properties配置文件获取,而logPrefix无论如何都不会从api-access-log.properties配置文件中读取

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值