1. 程式人生 > 實用技巧 >在spring配置檔案中引入外部properties配置檔案 context:property-placeholder

在spring配置檔案中引入外部properties配置檔案 context:property-placeholder

在spring的配置檔案中,有時我們需要注入很多屬性值,這些屬性全都寫在spring的配置檔案中的話,後期管理起來會非常麻煩。所以我們可以把某一類的屬性抽取到一個外部配置檔案中,使用時通用spring的EL表示式引入就可以了。這樣可以方便我們管理屬性。

步驟:

1.引入context名稱空間,並使用<context:property-placeholder location="外部配置檔案"/> 引入外部配置檔案

<?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
"> <context:component-scan base-package="com.xj"/> <context:property-placeholder location="classpath:jdbc.properties"/> </beans>

2.建立一個外部配置檔案jdbc.properties,並設定鍵值對

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/userDb
jdbc.userName=root
jdbc.password
=123456

3.在spring配置檔案中通過spEL表示式引入外部配置檔案jdbc.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
        ">

    <context:component-scan base-package="com.xj"/>

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

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.userName}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

</beans>