我目前正在构建一个小型Web应用程序,由于某些原因,它必须能够在仅支持Servlet 2.5和Java 6的旧服务器/容器上运行。此外,Web应用程序配置需要完全自包含,因此甚至不能使用系统变量和/或JVM参数。管理员只希望为每个环境提供一个.war文件,以便将其放入容器进行部署。
我在我的Web应用程序中使用了Spring 4.x。以下是我如何配置应用程序,使活动Maven配置文件用于设置活动的Spring 4.x配置文件。
pom.xml文件更改
我向我的POM文件添加了以下内容。我的POM使用模型版本4.0.0,并且在构建时我运行的是Maven 3.1.x。
<modelVersion>4.0.0</modelVersion>
...
<profiles>
<profile>
<id>dev</id>
<activation>
<!-- Default to dev so we avoid any accidents with prod! :) -->
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- This can be a single value, or a comma-separated list -->
<spring.profiles.to.activate>dev</spring.profiles.to.activate>
</properties>
</profile>
<profile>
<id>uat</id>
<properties>
<!-- This can be a single value, or a comma-separated list -->
<spring.profiles.to.activate>uat</spring.profiles.to.activate>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<!-- This can be a single value, or a comma-separated list -->
<spring.profiles.to.activate>prod</spring.profiles.to.activate>
</properties>
</profile>
</profiles>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<webResources>
<webResource>
<filtering>true</filtering>
<directory>src/main/webapp</directory>
<includes>
<include>**/web.xml</include>
</includes>
</webResource>
</webResources>
<failOnMissingWebXml>true</failOnMissingWebXml>
</configuration>
</plugin>
...
</plugins>
</build>
web.xml file changes
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-core-config.xml</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>${spring.profiles.to.activate}</param-value>
</context-param>
现在我可以创建基于Java的配置类,就像下面这个例子一样,只有在特定的Spring配置文件被激活时才会使用。
@Configuration
@Profile({"dev","default"})
@ComponentScan
@EnableTransactionManagement
@EnableSpringDataWebSupport
public class PersistenceContext {
}
spring.profiles.active
显式设置在一起,则前者将优先生效。 - secondbreakfast