spring boot:基于profile的多环境配置(spring boot 2.3.4)
一,为什么要进行多环境配置?
1,没有人会在生产环境中进行开发和测试,
所以通常会有多个环境的划分:
工程师本地的开发环境
进行测试的测试环境
最终上线的生产环境
每个环境对应不同的数据库/缓存等数据源和不同的接口
如果每次部署应用时都需要修改配置文件则会很不方便,
我们通过设置切换profile,可以使应用在不同的环境中调用相应的配置文件工作
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/25/spring-boot-ji-yu-profile-de-duo-huan-jing-pei-zhi-spring/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,演示项目的相关信息
1,项目地址:
https://github.com/liuhongdi/profile
2,功能说明:
演示了通过切换profile读取配置文件的属性
3,项目结构;如图:
三,配置文件说明
1,pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2,application.properties
custom.orig="application.properties" custom.active="application.properties" spring.profiles.active=dev
说明:spring.profiles.active用来指定默认使用的一个配置文件
3,application-prd.properties
custom.active="application-prd.properties"
4,application-dev.properties
custom.active="application-dev.properties"
四,java代码说明
1,HomeController.java
@Controller @RequestMapping("/home") public class HomeController { //读取变量custom.orig @Value("${custom.orig}") private String origstr; //读取变量custom.active @Value("${custom.active}") private String activestr; //打印从配置文件中读取到的变量值 @GetMapping("/home") @ResponseBody public String home() { return "this is home/home page<br/> active:"+activestr+"<br/> orig:"+origstr; } }
五,测试效果:
1,打包:
先执行clean
然后执行:package
2,测试执行:
从控制台执行:
[root@localhost profile]# java -jar target/demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=prd
然后访问页面:
http://127.0.0.1:8080/home/home
返回:
this is home/home page active:"application-prd.properties" orig:"application.properties"
可以看到当前application.properties和application-prd.properties都生效,
而两者中均存在的同名的变量生效的是application-prd.properties
3,修改profile为dev:
[root@localhost profile]# java -jar target/demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
返回:
this is home/home page active:"application-dev.properties" orig:"application.properties"
这次是application-dev生效
4,测试不指定profile
[root@localhost profile]# java -jar target/demo-0.0.1-SNAPSHOT.jar
返回:
this is home/home page active:"application-dev.properties" orig:"application.properties"
说明spring.profiles.active=dev指定默认的配置文件已生效
六,查看spring boot版本
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.4.RELEASE)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧