Spring Boot使用profile

Laughing
2021-06-06 / 0 评论 / 965 阅读 / 搜一下 / 正在检测是否收录...

开发者在项目发布之前,一般需要频繁的在开发环境、测试环境及生产环境之间进行切换,这个时候大量的配置需要频繁更改,例如数据库配置、 redis配置、mongodb 配置等。频繁修改带来巨大工作量,Spring对此提供了解决方案(@Profile注解), Spring Boot则更进一步提供了更加简洁的解决方案, Spring Boot中约定的不同环境下配置文件名称规则为application-{profile} .properties, profile占位符表示当前环境的名称,具体配置步骤如下。

创建配置文件

resources中创建两个配置文件,分别是application-dev.propertiesapplication-prod.properties,分别代表开发环境及正式环境的配置。

application-dev.properties

dev指定端口为8080

server.port=8080
server.servlet.context-path=/study
server.tomcat.basedir=log

application-prod.properties

prod指定端口为8081

server.port=8081
server.servlet.context-path=/study
server.tomcat.basedir=log

在application.properties中配置

spring.profiles.active=prod

在代码中配置

在启动类中设置

    public static void main(String[] args) {
//        SpringApplication.run(DemoApplication.class, args);
        SpringApplicationBuilder builder = new SpringApplicationBuilder(DemoApplication.class);
        builder.bannerMode(Banner.Mode.OFF);
        builder.application().setAdditionalProfiles("prod");
        builder.run(args);
    }

在项目启动时配置

java -jar demo-0.0.1-SNAPSHOT.jar --spring.profile.active=prod
0

评论 (0)

取消
  1. 头像
    青云
    Windows 10 · Google Chrome

    感谢分享

    回复