spring 笔记3: Spring 多环境配置文件切换
使用Spring进行开发时,需要面对不同的运行环境,比如开发环境、测试环境、生产环境等。大多时候不同的环境需要不同的配置文件。网上很多资料都是使用Spring的Bean definition profiles 功能来实现(https://docs.spring.io/spring/docs/4.2.4.RELEASE/spring-framework-reference/html/beans.html#beans-definition-profiles)。这种方式就会出现同一个Bean要正对不同的环境分别声明,即繁琐,又造成相同的配置要重复很多遍。
比如:需要在vmoption 里面增加 -Dspring.profiles.active=dev
<beans profile="dev"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:properties/config_dev.properties</value> </list> </property> </bean> </beans> <beans profile="test"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:properties/config_test.properties</value> </list> </property> </bean> </beans> <beans profile="uat"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:properties/config_uat.properties</value> </list> </property> </bean> </beans> <beans profile="product"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:properties/config_product.properties</value> </list> </property> </bean> </beans>
相比之下,我更喜欢这种方式:
需要vm option里面新增:-Denv=_rel。 如果没有新增属性,那么默认加载的是文件mybatis/jdbc.properties 。
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:mybatis/jdbc${env:}.properties</value> <value>classpath*:cache/radis${env:}.properties</value> <value>classpath*:applicationConfig${env:}.properties</value> <value>classpath*:rabbitmq/rabbitmq${env:}.properties</value> <value>classpath*:redisson/redisson${env:}.properties</value> <value>classpath*:webservice/webservice.properties</value> <value>classpath*:apiclient${env:}.properties</value> <value>classpath*:httprequest${env:}.properties</value> </list> </property> </bean>
仅就实现配置文件切换来说,两种方式中我倾向于后者,更简洁明了。当然前者有些功能是后者无法实现的,比如针对不同的环境有选择性的实例化对象。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?