2017-01-29 86 views
0

我有一個Spring 4 MVC應用程序,我想從命令行傳入環境(配置文件),並讓它在啓動時讀取正確的環境特定文件.properties在Spring MVC中設置環境/配置文件

這些屬性文件實質上包含不同的jdbc連接字符串,因此每個環境都可以連接到正確的數據庫。

我仍然在學習Spring和Java,所以很難弄明白這一點。

web.xml我定義3個環境/型材

<context-param> 
    <param-name>spring.profiles.active</param-name> 
    <param-value>test, dev, prod</param-value> 
</context-param> 

我有資源目錄下3環境中的特定文件。我的理解是,Spring將嘗試獲取適當的環境特定文件和通用的application.properties文件(如果存在,並且不在此處),以便重新使用。

> \ls src/main/webapp/resources/properties/ 
application-dev.properties application-prod.properties application-test.properties 

每個文件都非常簡單,只是該環境的jdbc連接參數。例如:

jdbc.driverClassName=org.postgresql.Driver 
jdbc.url=jdbc:postgresql://localhost:5432/galapagos 
jdbc.username=foo 
jdbc.password= 

最後在我的servlet文件spring-web-servlet.xml,我讀的應用程序屬性文件,並用它來建立連接

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 
    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 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> 

    .... 

    <!-- Database/JDBC --> 

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

    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
    <beans:property name="driverClassName" value="${jdbc.driverClassName}" /> 
    <beans:property name="url" value="${jdbc.url}" /> 
    <beans:property name="username" value="${jdbc.username}" /> 
    <beans:property name="password" value="${jdbc.password}" /> 
    </beans:bean> 

    .... 

</beans:beans> 

這示數出來,因爲它試圖尋找一個resources/properties/application.properties其不存在。但我不知道還有什麼要放在那裏。我如何在啓動時動態讀取正確的環境文件?

我看到一些例子like this one使用上下文監聽器,但老實說,我還在學習Spring MVC和真的不明白那些正在嘗試做的

謝謝!

回答

0

默認情況下,spring會嘗試找到resources/properties/application.properties來加載屬性。該文件是自動檢測的。 這是你的問題,你必須提供一個。如果您不想擁有application.properties文件,則可以通過使用spring.config.location環境屬性指定spring.config.name環境屬性及其位置來覆蓋它的名稱。

在你web.xml

<context-param> 
<param-name>spring.profiles.active</param-name> 
<param-value>test, dev, prod</param-value> 
</context-param> 

您在同一時間啓動3個配置文件。我建議您在application.properties中定義哪個配置文件已激活。例如:

spring.profiles.active=dev 

然後,將加載特定的環境文件並將優先於默認屬性文件。

+2

** Spring **不會尋找application.properties默認情況下,它是** Spring Boot **這樣做,請不要誤導他人 –