1. 程式人生 > >Spring引入外部properties檔案

Spring引入外部properties檔案

1、背景:Spring配置檔案需要通過context:property-placeholder標籤或者PropertyPlaceholderConfigurer類來引入classpath路徑下的properties檔案,示例如下:

<context:property-placeholder location="classpath:jdbc.properties" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property
name="locations" value="classpath:jdbc.properties"/>
</bean>

但像資料庫配置這種隨環境變化的檔案我們並不想打到war中,而是希望引入war包外的檔案。

2、方案context:property-placeholder標籤的location屬性還提供了file:http:ftp:三種字首,分別通過檔案路徑、HTTP資源和FTP資源引入檔案,詳見Spring官方文件。同時Spring支援#{systemProperties['config.location']}EL表示式,來引入自定義的系統變數config.location

,詳見Spring官方文件

3、示例:我的資料庫配置放到了Tomcat工作目錄的自定義目錄custom_config下,名為jdbc.properties,通過自定義Listener將custom_config的絕對路徑寫到系統變數中,然後在Spring配置檔案通過file:字首和#{systemProperties['config.location']}來找到jdbc.properties
Tomcat目錄

public class ConfigLocationListener implements ServletContextListener {
    private static Logger log = LoggerFactory.getLogger(ConfigLocationListener.class);

    @Override
public void contextInitialized(ServletContextEvent arg0) { log.info("init begin"); // 設定配置檔案路徑 String configFilePath = System.getProperty("catalina.home") + "/custom_config/"; // 設定配置檔案路徑的系統變數 System.setProperty("config.location", configFilePath); log.info("init end"); } @Override public void contextDestroyed(ServletContextEvent arg0) { log.info("destroy begin"); log.info("destroy end"); } }
<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-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:property-placeholder location="file:#{systemProperties['config.location']}jdbc.properties" />

    ... ...

</beans>