天天看點

Spring 架構加載外部檔案

  • 在配置檔案裡配置Bean時,有時需要在Bean的配置裡混入系統部署的細節資訊(如:檔案路徑,資料源資訊等),而這些細節需要和bean配置檔案分離。
  • Spring 提供了一個 PropertyPlaceholderConfigurer 的 BeanFactory 後置處理器,這個處理器運作使用者将Bean配值的部分内容移到外部檔案中。可以再Bean配置檔案裡使用形式為 ${var} 的變量,PropertyPlaceholderConfigurer 從屬性檔案裡加載屬性,并使用這些屬性來替換變量。
  • Spring 的屬性檔案中允許使用 ${properName},以實作屬性之間的引用。

注冊 PropertyPlaceholderConfigurer 的兩種方法

方法一:(spring 2.0)

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:db.properties"/>
</bean>
           

方法二:(spring 2.5之後,需要引入context的解析)

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

例子:

beans-properties.xml

<?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:property-placeholder location="classpath:db.properties"/>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}"></property>
        <property name="password" value="${password}"></property>
        <property name="jdbcUrl" value="${jdbcurl}"></property>
        <property name="driverClass" value="${driverclass}"></property>
    </bean>
</beans>
           

db.properties

user=root
password=
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql:///test
           

需要引入mysql的jdbc連接配接包和c3p0的jar包,maven配置

<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>
<!-- mysql驅動 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.34</version>
</dependency>
           

Main.java

package com.spring.test.properties;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-properties.xml");
        DataSource dataSource = (DataSource) ctx.getBean("dataSource");
        System.out.println(dataSource);
    }
}
           

Import

Spring 允許通過 <\import> 将多個配置檔案引入到一個檔案中,進行配置檔案的內建。

import 元素的 resource 屬性支援 Spring 的标準的路徑資源

Spring 架構加載外部檔案

繼續閱讀