栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

SpringBoot | 第五章:多环境配置

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot | 第五章:多环境配置

前言

写上一篇看英文资料,耗费了心力呀,这章,相对来说简单点。也比较熟悉,但是这很实用。不扯了,开始~

多环境配置

在开发应用时,常用部署的应用是多个的,比如:开发、测试、联调、生产等不同的应用环境,这些应用环境都对应不同的配置项,比如swagger一般上在生产时是关闭的;不同环境数据库地址、端口号等都是不尽相同的,要是没有多环境的自由切换,部署起来是很繁琐也容易出错的。

maven的多环境配置

在没有使用过springboot的多环境配置时,原先是利用maven的profile功能进行多环境配置,这里我简单回顾下。

maven配置

   
       
          dev
          
                true
            
            
               8080
            
       
       
          test
            
               8888
            
              
    
    
    
        
            src/main/resources
            
                ***.properties
            
            
            true
        
    
    
        
            maven-resources-plugin
            
                utf-8
                
                true
            
        
        
            org.springframework.boot
            spring-boot-maven-plugin
        
    
    

然后编译时,加入-Ptest,则会替换test环境下的参数值。
完整参数:

 mvn clean install -DskipTests -Ptest

application.properties

server.port=${pom.port}

利用maven实现多环境配置,比较麻烦的就是每次部署新环境时,都需要再次指定环境编译打包一次。一下进入主题,springboot的多环境,比较优雅了许多。

springboot多环境配置

Profile是Spring针对不同环境不同配置的支持。需要满足application-{profile}.properties,{profile}对应你的环境标识。如:

  • application-dev.properties:开发环境

  • application-test.properties:测试环境

image

而指定执行哪份配置文件,只需要在application.properties配置spring.profiles.active为对应${profile}的值。

# 指定环境为devspring.profiles.active=dev

则会加载:application-dev.properties的配置内容。

2018-07-15 14:52:41.304  INFO 15496 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-07-15 14:52:41.310  INFO 15496 --- [           main] c.l.l.s.chapter5.Chapter5Application     : Started Chapter5Application in 8.506 seconds (JVM running for 10.81)
2018-07-15 14:52:41.316  INFO 15496 --- [           main] c.l.l.s.chapter5.Chapter5Application     : 多环境应用启动.

还可以在命令行方式激活不同环境配置,如

java -jar xxx.jar --spring.profiles.active=test

此时就会加载application-test.properties的配置内容。
test:

test


dev:

dev


这里顺便提一句,可能在不同环境下,可能加载不同的bean时,可利用@Profile注解来动态激活

@Profile("dev")//支持数组:@Profile({"dev","test"})@Configuration@Slf4jpublic class ProfileBean {    @PostConstruct
    public void init() {
        log.info("dev环境下激活");
    }    
}

启动时。控制台输出:

2018-07-15 15:04:44.540  INFO 11876 --- [           main] c.l.l.springboot.chapter5.ProfileBean    : dev环境下激活
总结

目前互联网上很多大佬都有springboot系列教程,如有雷同,请多多包涵了。本文是作者在电脑前一字一句敲的,每一步都是亲身实际过的。若文中有所错误之处,还望提出,谢谢。



作者:oKong
链接:https://www.jianshu.com/p/947a92b77e33


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235921.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号