2017-01-29 85 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 **这样做,请不要误导他人 –