我有一個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和真的不明白那些正在嘗試做的
謝謝!
** Spring **不會尋找application.properties默認情況下,它是** Spring Boot **這樣做,請不要誤導他人 –