Spring应用 2 profile加载不同环境配置
profile的应用
通过Spring profile属性可以帮助我们快速方便的切换环境。使得开发、测试、生产环境得到快速切换。
1.不同环境加载不同的配置文件(数据库连接地址、api接口、用户密码等)
2.不同环境加载不同的接口实现类(数据源、业务逻辑、结果处理)
3.不同环境定义不同的日志级别
通过下面的示例中,
可以通过profile可以选择加载不同的配置文件,需要将不同环境的配置文件放置在不同的目录下。
可以在不同环境下加载不同的数据源和工具。例如在开发环境,数据源可能是txt文本,但是在线上环境的数据源就能自动替换成mysql 的数据源。
可以提供不同的工具,例如在开发环境需要将数据落地到本地txt,在线上环境则需要更新到mysql数据库中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<beans profile="dev">
<bean id="instance" class="com.mdq.util.DevInstance" />
<bean id="dataSourse" class="com.mdq.data.TxtDataSource" />
<context:property-placeholder location="classpath*:dev/*.properties" ignore-unresolvable="true" />
</beans>
<beans profile="prod">
<bean id="instance" class="com.mdq.util.ProdInstance" />
<bean id="dataSourse" class="com.mdq.data.MysqlDataSource" />
<context:property-placeholder location="classpath*:test/*.properties" ignore-unresolvable="true" />
</beans>
//以下两个实例不受profile的影响,和正常情况下加载实例一样。
<bean id="common1" class="com.mdq.util.Common1" />
<bean id="common2" class="com.mdq.util.Common2" />
</beans>