spring配置文件、组件读取外部properties文件方式;PropertiesFactoryBean和PropertyPlaceholderConfigurer的区别

时间:2019-12-12
本文章向大家介绍spring配置文件、组件读取外部properties文件方式;PropertiesFactoryBean和PropertyPlaceholderConfigurer的区别,主要包括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.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方法

  

 

原文地址:https://www.cnblogs.com/jetqiu/p/12028719.html