根据环境装配你的bean——Spring中profile的应用

来源:互联网 发布:c语言库函数大全pdf 编辑:程序博客网 时间:2024/06/07 07:27

  环境配置类注解的使用场景在于:有时候你的开发环境所使用的bean和测试环境以及生产环境不太一样,一般处理这类问题 可能需要人工处理,你可能会在环境迁移的时候手动去掉其他环境的注入标识,费时且容易出错。

  举一个例子:

  数据库配置,多个环境的数据库配置肯定不一样,datasource类bean需要手动去切换,如果项目有多数据源 那就更麻烦了。也可能在开发阶段,我需要一个嵌入式的Hypersonic数据库来产生调试数据,但在生产阶段,我就无须再这么做了。


而profile以及更高级的条件化装配机制,正是解决上诉问题的好方法。

在spring3.1版本引入了bean profile功能,请确保你的spring高于此版本

基于profile机制,你无须再单独构建不同的环境,且更改环境不需要重新编译你的war包,因为profile是运行时再来决定该创建哪些bean和不该创建哪些bean。

下面介绍如何使用profile

简而言之就是,首先你需要将不同bean定义整理到一个或多个profile中去,在应用部署时,决定哪个profile处于激活(active)状态。

@profile注解可以和@bean与@conponent联合使用,例如:


package com.csnt.scdp.bizmodules.interceptors;import com.csnt.scdp.bizmodules.attributes.CommonAttribute;import com.csnt.scdp.framework.helper.SessionFactoryHelper;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.beans.factory.config.ConfigurableBeanFactory;import org.springframework.context.annotation.Profile;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Component;@Aspect@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)@Profile("dev")@Componentpublic class AnnotationSessionAop {    private String currentSessionFactory;}

当@Profile加在bean的类文件上时,该bean会在名为"dev"的环境激活时创建。

当然如果你采用javaConfig来配置IOC的话,@Profile也可以加在你的配置类上,此时"dev"环境激活时,配置类所管理的bean才会被创建

在Spring3.2时,@Profile可以用在方法级别上

例如在javaConfig配置类中,使用构造器注入时,在方法上加入@Profile。这个效果和使用类自动扫描注入时加在待注入的bean类上是一样的。

需要注意的是,没有使用profile管理的bean,自始至终都会被创建,与profile的激活没有关系


如果你的spring是基于XML来配置的话,可以通过<eans>元素的profile属性来配置,例如

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns="http://www.springframework.org/schema/beans"       xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"       profile="dev"></beans>
<beans>中的profile属性也可嵌套使用,例如

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns="http://www.springframework.org/schema/beans"       xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">  <beans profile="dev">    <bean id="dataSource#1" class="bitronix.tm.resource.jdbc.PoolingDataSource" init-method="init" destroy-method="close">      ....    </bean>  </beans></beans>

配置好profile之后,下一步则是激活profile,通过设置spring.profiles.active和spring.profiles.default属性,前者优先级会高于后者。且只会存在一个值

有多种方式可以设置该属性:

1.作为DispatcherServlet的初始化参数

2.作为WEB应用上下文参数

3.作为JNDI条目

4.作为环境变量

5.作为JVM的系统属性

6.在集成测试类上,使用@ActiveProfiles注解(需要spring集成测试环境)

例如第一种配置方式,在web.xml中配置下列代码:(在DispatcherServlet中加入参数)

<servlet>        <servlet-name>scdp-dispatcher</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>spring.profiles.default</param-name>            <param-value>dev</param-value>        </init-param>        <load-on-startup>1</load-on-startup></servlet>

第二种配置方式,在web.xml中配置下列代码:(在web context上下文中配置参数)

<context-param>        <param-name>spring.profiles.default</param-name>        <param-value>dev</param-value></context-param>


可以在param-value 启动多个环境,名称用逗号分隔即可

第三种,如果使用javaConfig配置的话,则在AbstractAnnotationConfigDispatcherServletInitializer的子类里 重写onStartup方法,如下:

@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {super.onStartup(servletContext);servletContext.setInitParameter("spring.profiles.active", "live");//Set multiple active profile//servletContext.setInitParameter("spring.profiles.active", "dev, testdb");}


亦或是重写createRootApplicationContext方法,在context创建时将环境变量传入:

      //如果RootApplicationContext需要加载带有@Profile的bean时,例如spring的ApplicationContext配置类@Overrideprotected WebApplicationContext createRootApplicationContext() {WebApplicationContext context =                     (WebApplicationContext)super.createRootApplicationContext();    ((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles("live");//Set multiple active profiles//((ConfigurableEnvironment)context.getEnvironment())                //          .setActiveProfiles(new String[]{"live", "testdb"});    return context;}//如果ServletApplicationContext需要加载带有@Profile的bean时,例如springMVC的配置类/*@Overrideprotected WebApplicationContext createServletApplicationContext() {WebApplicationContext context =                     (WebApplicationContext)super.createServletApplicationContext();    ((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles("dev");    return context;}*/






原创粉丝点击