Spring框架之<context:property-placeholder />元素

来源:互联网 发布:大数据技术入门 编辑:程序博客网 时间:2024/05/21 13:59
原文链接:http://blog.sina.com.cn/s/blog_4550f3ca0100ubmt.html

感谢@JavaLeader 的总结


<context:property-placeholder />是Spring中一个较为常见的元素;

1. 应用场景:开发工作中变化频繁的一些变量,我们不希望每次改变它们之后重启程序,所以用配置文件的形式进行管理;

        例如:为了方便调试和开发,我们将程序的数据库配置信息写在配置文件database.properties中:

    #jdbc配置

    dataSource.driverClass=com.mysql.jdbc.Driver
    dataSource.jdbcUrl=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf8
    dataSource.user=user
    dataSource.password=user

    spring配置文件通过<context:property-placeholder location="classpath:config/database.properties" />读取连接信息

   这样就能通过${}的形式为bean设置属性值了。

    <!-- 配置数据源 -->

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

      <property name="driverClassName" value="${dataSource.driverClass}" />

      <property name="url" value="${dataSource.jdbcUrl}" />

       <property name="username" value="${dataSource.user}" /

       <property name="password" value="${dataSource.password}" />

    </bean>

2. 利用PropertyPlaceholderConfigurer篡改从属性文件读到的值;

     有的时候我们需要在读取到属性文件的值之后,对这些值进行加工再利用,我们就可以用PropertyPlaceholderConfigurer类来做。

             例如:我们希望将属性文件进行加密,此时我们就可以重载PropertyPlaceholderConfigurer类的processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)方法来对属性值解密操作;





0 0