Spring的PropertyPlaceholderConfigurer事例应用

在开发的过程中,经常发现一些类似:${log4j.level}之类的内容,后来才知道原因。下面解释一下:

1、PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是BeanFactoryPostProcessor接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进行修改,而不用对xml配置文件进行修改。

2、在Spring中,使用PropertyPlaceholderConfigurer可以在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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:component-scan base-package="com.***.data.***" />
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>classpath:project.properties</value>
        </property>
    </bean>
    <import resource="classpath*:/db/*.xml" />
    <import resource="classpath*:/common/*.xml" />
</beans>

2、文件antx.properties:

session.mode=test
session.userId=99758820
session.testDate=2013-07-17

3、在其他的xml文件里可以这么写:

        <bean id="sessionConfig" class="com.***.data.***.acl.SessionConfig">
                <property name="mode">
                        <value>${session.mode}</value>
                </property>
                <property name="userId">
                        <value>${session.userId}</value>
                </property>
                <property name="testDate">
                        <value>${session.testDate}</value>
                </property>
        </bean>

4、这样,一个简单的数据源就设置完毕了。可以看出:PropertyPlaceholderConfigurer起的作用就是将占位符指向的数据库配置信息放在bean中定义的工具。

5、当然也可以在JAVA代码中使用

private static final Properties sysConfig = new Properties();

    static {
        try {
            InputStream iStream = new FileInputStream(new File("config", "antx.properties"));
            sysConfig.load(iStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static String getPropertyValue(String key){
        return sysConfig.getProperty(key);
    }

 

 

转载于:https://www.cnblogs.com/liqiu/p/3412961.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值