當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring使用外部属性文件
生活随笔
收集整理的這篇文章主要介紹了
Spring使用外部属性文件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、在 Spring Config 文件中配置 Bean 時,有時候需要在 Bean 的配置里添加?系統(tǒng)部署的細節(jié)信息,?如文件路徑,數(shù)據(jù)源配置信息。而這些部署細節(jié)實際上需要在配置文件外部來定義。
二、Spring 提供了一個 PropertyPlaceholderConfigurer 的 BeanFactory 后置處理器。這個處理器允許用戶將 Bean 的配置部分內(nèi)容外移到屬性文件中,然后可以在 Bean 的配置文件
里使用形式為 ${var}的變量,PropertyPlaceholderConfigurer 從屬性文件里加載屬性,并使用這些屬性來替換變量。
三、Spring 還允許在屬性文件中使用 ${key},以屬性間的互相引用。
四、使用:需要注冊?PropertyPlaceholderConfigurer?。通過?<context:property-placeholder location="props.properties"/>?這種方式來指定屬性文件。
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="root"/> <property name="password" value="lgh123"/> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?user=root&password=lgh123&useUnicode=true&characterEncoding=UTF8&useSSL=true"/> </bean>--> <!--導入屬性文件--> <context:property-placeholder location="classpath:db.properties"/> <!--使用外部的屬性文件的屬性配置--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${user}"/> <property name="password" value="${password}"/> <property name="driverClass" value="${driverClass}"/> <property name="jdbcUrl" value="${jdbcUrl}"/> </bean> </beans>
db.properties
user=root password=lgh123 driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/test?user=root&password=lgh123&useUnicode=true&characterEncoding=UTF8&useSSL=true
測試:
package com.xiya.spring.beans.properties; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.sql.DataSource; import java.sql.SQLException; /** * Created by N3verL4nd on 2017/3/22. */ public class Main {public static void main(String[] args) throws SQLException {ApplicationContext context = new ClassPathXmlApplicationContext("beans-properties.xml"); DataSource dataSource = (DataSource) context.getBean("dataSource"); System.out.println(dataSource.getConnection()); } }
轉(zhuǎn)載于:https://www.cnblogs.com/lgh1992314/p/6616201.html
總結(jié)
以上是生活随笔為你收集整理的Spring使用外部属性文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win7 64位系统怎么分区 win7系
- 下一篇: jquery表格复选框简单练习及prop