继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

第十二节:Springboot多环境配置

入门小站
关注TA
已关注
手记 70
粉丝 2
获赞 4

开发的阶段会需要设定基本的属性或是自定义的属性,而且通常会被应用和安装到几个不同的环境上,比如:开发(dev)、测试(test)、生产(prod)等,其中对应的每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误。

通常有下面两种配置方式

1.maven的多环境配置

在没有使用过Spring Boot的多环境配置时,是用maven的profile功能进行多环境配置。

maven配置pom.xml

<profiles>
       <profile>
          <id>dev</id>
          <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
               <pom.port>8080</pom.port>
            </properties>
       </profile>
       <profile>
          <id>test</id>
            <properties>
               <pom.port>8888</pom.port>
            </properties>
       </profile>
</profiles>
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
    <plugins>
        <!--这个很重要-->
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
                <encoding>utf-8</encoding>
                <!-- 需要加入,因为maven预设的是${},而springbooot 预设会把此替换成@{} -->
                <useDefaultDelimiters>true</useDefaultDelimiters>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

application.properties的配置

server.port=${pom.port}

编译打包项目

> mvn clean install -DskipTests -Ptest

-Ptest表示编译为测试环境,对应<profile>下的<id>test</id>

2.SpringBooot的多环境配置

在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识。

application-dev.properties:开发环境
application-test.properties:测试环境
application-prod.properties:生产环境

而决定使用哪种环境的的配置文件,需要在application.properties中通过spring.profiles.active属性来设定,其值对应{profile}值。

application.properties的配置

# 指定dev開發環境
spring.profiles.active=dev

spring.profiles.active=dev 就会载入application-dev.properties 配置文件内容

测试

三个配置文件application-dev.propertiesapplication-test.propertiesapplication-prod.properties

三个文件的 server.port属性不一样,

  • application-dev.properties server.port=8081
  • application-test.properties server.port=8082
  • application-prod.properties server.port=8080

运行测试

# 运行端口被改成8081
> java -jar rumenz.jar --spring.profiles.active=dev  

# 运行端口被改成8082
> java -jar rumenz.jar --spring.profiles.active=test


# 运行端口被改成8080
> java -jar rumenz.jar --spring.profiles.active=prod

本小结源码地址:

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP