我目前正在构建一个小型 webapp(由于我无法控制的原因)必须能够在仅支持 Servlet 2.5 和 Java 6 的旧服务器/容器上运行。还需要 webapp 配置完全独立,因此即使是系统变量和/或 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 文件更改
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Setup for root Spring context
-->
<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>
<!--
Jim Tough - 2016-11-30
Per Spring Framework guide: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-environment
...profiles may also be activated declaratively through the spring.profiles.active
property which may be specified through system environment variables, JVM system
properties, servlet context parameters in web.xml, or even as an entry in JNDI.
-->
<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 {
// ...
}