spring应用手册-IOC(XML配置实现)-(19)-beans标签的profile属性

    科技2022-07-11  115

    戴着假发的程序员出品

    beans标签的profile属性

    spring应用手册(第一部分)

    profile用于配置spring的多环境配置。

    我们可以通过profile配置多个不同环境下的配置属性。

    案例:

    <?xml version="1.0" encoding="UTF-8"?> <beans default-autowire="byName" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <beans profile="test"> <!-- 测试环境下的配置 --> </beans> <beans profile="prod"> <!-- 生产环境下的配置 --> </beans> </beans>

    spring 为我们提供了大量的激活 profile 的方法,可以通过代码来激活,也可以通过系统环境变量、JVM参数、servlet上下文参数来定义 spring.profiles.active 参数激活 profile。

    ENV方式:ConfigurableEnvironment.setActiveProfiles(“test”)

    JVM参数方式:set JAVA_OPTS="-Dspring.profiles.active=test"

    web.xml方式:

    <init-param> <param-name>spring.profiles.active</param-name> <param-value>production</param-value> </init-param>

    标注方式(junit单元测试非常实用):

    @ActiveProfiles({"unittest","productprofile"})

    看案例:

    我们配置如下,不同的环境下在service中注入不同的dao:

    <?xml version="1.0" encoding="UTF-8"?> <beans default-autowire="byType" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 注册accountDAO_mysql --> <bean id="accountDAO_mysql" autowire-candidate="false" class="com.dk.demo1.dao.impl.AccountDAO_mysql"/> <!-- 注册accountDAO_oracle --> <bean id="accountDAO_oracle" class="com.dk.demo1.dao.impl.AccountDAO_oracle"/> <beans profile="mysql"> <!-- 注册accountService 注入accountDAO_mysql --> <bean id="accountService" name="a_service" class="com.dk.demo1.service.AccountService"> <property name="accountDAO" ref="accountDAO_mysql"/> </bean> </beans> <beans profile="oracle"> <!-- 注册accountService 注入accountDAO_mysql --> <bean id="accountService" name="a_service" class="com.dk.demo1.service.AccountService"> <property name="accountDAO" ref="accountDAO_oracle"/> </bean> </beans> </beans>

    测试:

    @Test public void testSpringProfile(){ //创建spring容器 ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //激活profile ConfigurableEnvironment environment = ac.getEnvironment(); environment.setActiveProfiles("oracle"); //重启容器 ac.refresh(); AccountService accountService = ac.getBean(AccountService.class); accountService.save("戴着假发的程序员"); }
    Processed: 0.009, SQL: 8