zoukankan      html  css  js  c++  java
  • spring配置文件、组件读取外部properties文件方式;PropertiesFactoryBean和PropertyPlaceholderConfigurer的区别

    一、spring配置文件、组件读取外部properties文件方式

    -- spring配置文件
    <bean id="mySqlDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="username"><value>${jdbc.user}</value></property> <property name="password"><value>${jdbc.password}</value></property> <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property> <property name="url"><value>${jdbc.url}</value></property> </bean>
    -- properties文件内容 jdbc.url
    =jdbc:mysql://localhost:3306/cp?useUnicode=true&amp;charaterEncoding=utf-8 jdbc.user=root jdbc.password=123456 jdbc.driverClass=com.mysql.jdbc.Driver

    方式一、

    在 spring 的配置文件中,加入引入until命名空间:

    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/util
            http://www.springframework.org/schema/util/spring-util-3.0.xsd"
    <util:properties id="propertiesReader" location="classpath:test.properties" /> 

    方式二、

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

    方式三、读取多个 properties 文件

    <bean id="propertiesReader"
    class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="locations">
        <list>
             <!--只会到项目class路径中查找找文件-->
          <value>classpath:*.properties</value>
    
         <!--不仅会到当前项目class路径,还会到包括jar文件中(class路径)进行查找; 推荐第一种,比较快-->
         <!--<value>classpath:*.properties</value>-->
        </list>
      </property>
    </bean>

    <bean id="propertiesReader"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
        <list>
             <!--只会到项目class路径中查找找文件-->
          <value>classpath:*.properties</value>
    
         <!--不仅会到当前项目class路径,还会到包括jar文件中(class路径)进行查找; 推荐第一种,比较快-->
         <!--<value>classpath:*.properties</value>-->
        </list>
      </property>
    </bean>

    二、PropertiesFactoryBean和PropertyPlaceholderConfigurer的区别如下:

    使用 PropertyPlaceholderConfigurer 时,spring组件取值时 @Value表达式的用法是 @Value(value="${properties key}") ,

    使用 PropertiesFactoryBean 时,spring组件取值时@Value表达式的用法是 @Value(value="#{configProperties['properties key']}")

    @Value(value="${profit.rate.csProfitRate}")
    double rate;
     
    @Value(value="#{configProperties['profit.rate.csProfitRate']}")
    double rate2;
    
    // 变量要有getter和setter方法

      

     

  • 相关阅读:
    开源一些C#不常用知识(附上DEMO)
    开源:C# 代码自动生成工具,支持站点前后台
    Xposed 集成 Android 6.0.1环境中,总结
    Android 视频通信,低延时解决方案
    Android studio,第一个生成,调用成功的jni(说多了都是泪)
    C#之文件缓存
    JavaScript 基本常识
    排序算法
    LeetCode:字符串转换整数 (atoi)
    LeetCode:判断回文数
  • 原文地址:https://www.cnblogs.com/jetqiu/p/12028719.html
Copyright © 2011-2022 走看看