使用Spring Boot时,通过web.xml的context-param来指定spring.profiles.active

暂时创建一个随意的pom.xml。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>kagamihoge</groupId>
    <artifactId>asdasdf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>asdasdf</name>
    <description>Add project description here</description>

    <properties>
        <maven.war.filteringDeploymentDescriptors>true</maven.war.filteringDeploymentDescriptors>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

    <profiles>
        <profile>
            <id>hoge</id>
            <properties>
                <spring_profile_value>hoge_profile</spring_profile_value>
            </properties>
        </profile>
    </profiles>
</project>

通过使用…,可以使maven-war-plugin替换web.xml中的占位符。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>@spring_profile_value@</param-value>
    </context-param>

</web-app>

在web.xml的context-param中指定由Maven的profile指定的spring.profiles.active。在Spring Boot中,Maven的占位符引用不是${…},而是@…@。

只需要进行mvn package -P hoge等操作,生成的war包中的web.xml将会是这样的。

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>hoge_profile</param-value>
</context-param>

然而,即使在参考的”How to set spring active profiles with maven profiles”中也提到,使用这种方式切换活动配置文件并不算美观。原因是,这会导致每个环境生成不同内容的war文件,而最好只有一个最终二进制文件,这样可以减少一些问题。

我想说的是虽然现实世界有许多不同的情况,不能一概而论通过web.xml进行指定是不好的。

请提供网址参考。

    • https://stackoverflow.com/questions/25420745/how-to-set-spring-active-profiles-with-maven-profiles

 

    • https://stackoverflow.com/questions/15355708/how-to-replace-a-value-in-web-xml-with-a-maven-property

 

    https://memorynotfound.com/servlet-3-web-xml-example-configuration/
bannerAds