SpringBoot多环境配置

本文详细介绍如何在SpringBoot项目中实现多环境配置,包括开发、测试和生产环境的数据库地址、服务器端口等参数的灵活切换。通过使用application-{profile}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 背景:

在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。

  • 解决方式:

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

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

    至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值

  • @Profile实现业务逻辑根据环境不同

  • 首先定义一个接口:

    • public interface EnvService {    
          public String getActiveProfile();
      }
      
  • 然后定义几个实现类:

    • 开发环境:

      @Service
      @Profile("dev")
      public class EnvDevService implements EnvService{    
          @Override    
          public String getActiveProfile() {        
              return "dev";    
          }
      }
      
    • 生产环境:

      @Service
      @Profile("prod")
      public class EnvProdService implements EnvService{    
          @Override    
          public String getActiveProfile() {        
              return "prod";    
          }
      }
      
    • 测试环境:

      @Service
      @Profile("test")
      public class EnvTestService implements EnvService{    
          @Override    
          public String getActiveProfile() {        
              return "test";    
          }
      }
      
  • 使用:

     if("test".equalsIgnoreCase(envService.getActiveProfile())){
         hostUrl = AD_TEST_HOST;
     } else {
         hostUrl = AD_HOST;
     }
    

    代码执行到这,会根据application.xml中配置的spring.profiles.active=XXX,去选择执行具体哪个实现类;例如配置的是spring.profiles.active=dev,则调用的就是@Profile(“dev”)对应的实现类。

  • 启动jar包时,启动脚本中经常看到类似以下启动命令:

nohup java -jar  /data/server/ifsmp/ifsmp.war --spring.profiles.active=test --server.port=8080 >/dev/null 2>&1 &

其中 --spring.profiles.active=test就是使用对应的application-test.properties配置文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值