Spring教程 - Spring Place Holder属性

2018-01-09 19:06 更新

Spring教程 - Spring Place Holder属性


PropertyPlaceholderConfigurer 类可以外部化将部署详细信息导入属性文件。

然后我们可以从bean配置文件访问它的值通过特殊格式: $ {variable}

以下代码显示将数据库连接属性放在单独的文件中。

数据库属性文件

以下代码创建sa属性文件(database.properties)。它包括数据库连接详细信息。我们可以把它放到项目类路径中。

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/java2sjava
jdbc.username=root
jdbc.password=password

以下xml配置文件使用PropertyPlaceholderConfigurer映射“database.properties"属性文件。

<bean  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
   <value>database.properties</value>
   </property>
</bean>

这是完整的xml配置文件。

<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-2.5.xsd">
  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
      <value>database.properties</value>
    </property>
  </bean>
  <bean id="customerDAO" class="com.java2s.customer.dao.impl.JdbcCustomerDAO">
    <property name="dataSource" ref="dataSource" />
  </bean>
  <bean id="customerSimpleDAO" 
                class="com.java2s.customer.dao.impl.SimpleJdbcCustomerDAO">
    <property name="dataSource" ref="dataSource" />
  </bean>
  <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
  </bean>
</beans>


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号