Spring属性占位符PropertyPlaceholderConfigurer

       通常在Spring项目中如果用到配置文件时,常常会使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer来简化代码,例如:
<bean id="aaa" class="com.zero.spring.SpringIoc.test.AAA">
    <property name="name" value="zero"/>
    <property name="gender">
        <value>man</value>
    </property>
</bean>
我们希望将name、gender的值写在配置文件中,以后的改动只需要对配置文件进行修改即可,于是就会用到PropertyPlaceholderConfigurer:
test.properties
name=zero
gender=man
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <bean id="propertyConf" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="test.properties"/>
    </bean>
    
    <bean id="aaa" class="com.zero.spring.SpringIoc.test.AAA">
        <property name="name" value="${name}"/>
        <property name="gender">
            <value>${gender}</value>
        </property>
    </bean>

</beans>
这里可以更简化我们的配置,使用<context:property-placeholder/>,它会自动加载PropertyPlaceholderConfigurer这个Bean(详细请看源码),于是就有了如下的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="test.properties"/>

    <bean id="aaa" class="com.zero.spring.SpringIoc.test.AAA">
        <property name="name" value="${name}"/>
        <property name="gender">
            <value>${gender}</value>
        </property>
    </bean>
</beans>

<context:property-placeholder/>其它参数如下:
<context:property-placeholder   
        location="属性文件,多个之间逗号(,)分隔"  
        file-encoding="文件编码"  
        ignore-resource-not-found="是否忽略找不到的属性文件,默认false,即不忽略,找不到将抛出异常"  
        ignore-unresolvable="是否忽略解析不到的属性,如果不忽略,找不到将抛出异常"  
        properties-ref="本地Properties配置"  
        local-override="是否本地覆盖模式,即如果true,那么properties-ref的属性将覆盖location加载的属性,否则相反"  
        system-properties-mode="系统属性模式,默认ENVIRONMENT(表示先找ENVIRONMENT,再找properties-ref/location的),NEVER:表示永远不用ENVIRONMENT的,OVERRIDE类似于ENVIRONMENT"  
        order="顺序,当配置多个<context:property-placeholder/>时的查找顺序"  
        />  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值