美文网首页
SpringBoot 多环境

SpringBoot 多环境

作者: 侧耳倾听y | 来源:发表于2021-03-25 13:12 被阅读0次

spring的多环境配置

不同环境新建不同的配置文件,例如dev环境,新建一个名为application-dev.properties的文件,而application.properties文件中,可以放一些相同的配置。项目启动时,在application.properties添加spring.profiles.active属性,激活对应的环境。

application.properties:

spring.profiles.active=dev

application-dev.properties

test.value=222

application-test.properties:

test.value= 1111

TestService.java

package com.example.profiletest.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class TestService {


    @Value("${test.value}")
    private String value;


    public String get(){
        return value;
    }
}

启动项目后,当spring.profiles.active参数不同时,value也不同。
也可以使用-Dspring.profiles.active=dev这方式。

maven的多环境配置

pom文件

   <build>
        <filters>
            <!-- 这里的文件名必须与多环境配置文件的文件名相同, ${env} 会动态获取不同环境 -->
            <!-- 假如激活 dev 环境, 这时对应的文件就是 src/main/filters/application-dev.properties -->
            <filter>src/main/filters/application-${env}.properties</filter>
        </filters>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <!-- 是否替换资源中的属性, 设置为 true 才能实现动态替换 -->
                <filtering>true</filtering>
            </resource>
        </resources>
  </build>

  <profiles>
        <profile>
            <id>dev</id>
            <properties>
                <!-- env 必须与文件的后缀一致(application-${env}.properties) -->
                <!-- 其中 env 这个标签也可以自定义, 没有强制要求必须是 env,但必须与上面 application-${env}.properties 的 ${} 里的值一致 -->
                <env>dev</env>
            </properties>
            <!-- 不指定环境则默认 dev 环境, 可以放在任一个环境下, 但不能在多个环境中指定 -->
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>

        <profile>
            <id>test</id>
            <properties>
                <env>test</env>
            </properties>
        </profile>
    </profiles>

application.properties:

test.value=@test.value@

application-dev.properties

test.value=222

application-test.properties:

test.value= 1111
项目目录

本地启动项目可以在idea右侧选择环境。打包时候可以使用命令:mvn clean package -Pdev。

注意:

由于${}方式会被maven处理。如果你pom继承了spring-boot-starter-parent,
Spring Boot已经将maven-resources-plugins默认的${}方式改为了@@方式,如@name@

如果还想继续使用${}占位符方式,只需要在pom文件中加上下面配置即可:

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>utf-8</encoding>
                    <useDefaultDelimiters>true</useDefaultDelimiters>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

相关文章

网友评论

      本文标题:SpringBoot 多环境

      本文链接:https://www.haomeiwen.com/subject/evscvktx.html