- 背景:
在开发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配置文件