原文地址:http://gordondickens.com/wordpress/2012/06/12/spring-3-1-environment-profiles/

Profiles

Spring 3.1 now includes support for the long awaited environment aware feature called profiles. Now we can activate profiles in our application, which allows us to define beans by deployment regions, such as “dev”, “qa”, “production”, “cloud”, etc.

We also can use this feature for other purposes: defining profiles for performance testing scenarios such as “cached” or “lazyload”.

Essential Tokens

Spring profiles are enabled using the case insensitive tokens spring.profiles.active orspring_profiles_active.

This token can be set as:

  • an Environment Variable
  • a JVM Property
  • Web Parameter
  • Programmatic

Spring also looks for the token, spring.profiles.default, which can be used to set the default profile(s) if none are specified with spring.profiles.active.

Grouping Beans by Profile

Spring 3.1 provides nested bean definitions, providing the ability to define beans for various environments:

?
1
2
3
4
<beans profiles="dev,qa">
  <bean id="dataSource" class="..."/>
  <bean id="messagingProvider" class="..."/>
</beans>

Nested <beans> must appear last in the file. 
Beans that are used in all profiles are declared in the outer <beans> as we always have, such as Service classes.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:c="http://www.springframework.org/schema/c"
       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">
    <bean id="businessService"
       class="com.c...s.springthreeone.business.SimpleBusinessServiceImpl"/>
    <beans profile="dev,qa">
        <bean id="constructorBean"
          class="com.gordondickens.springthreeone.SimpleBean"
              c:myString="Constructor Set"/>
        <bean id="setterBean"
          class="com.gordondickens.springthreeone.SimpleBean">
            <property name="myString" value="Setter Set"/>
        </bean>
    </beans>
    <beans profile="prod">
        <bean id="setterBean"
          class="com.gordondickens.springthreeone.SimpleBean">
            <property name="myString" value="Setter Set - in Production YO!"/>
        </bean>
    </beans>
</beans>

If we put a single <bean> declaration at below any nested <beans> tags we will get the exception org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'bean'.

Multiple beans can now share the same XML “id” 
In a typical scenario, we would want the DataSource bean to be called dataSource in both all profiles. Spring now allow us to create multiple beans within an XML file with the same ID providing they are defined in different <beans> sets. In other words, ID uniqueness is only enforced within each <beans> set.

Automatic Profile Discovery (Programmatic)

We can configure a class to set our profile(s) during application startup by implementing the appropriate interface. For example, we may configure an application to set different profiles based on where the application is deployed – in CloudFoundry or running as a local web application. In the web.xml file we can include an Servlet context parameter,contextInitializerClasses, to bootstrap this class:

?
1
2
3
4
<context-param>
  <param-name>contextInitializerClasses</param-name>
  <param-value>com.gordondickens.springthreeone.services.CloudApplicationContextInitializer</param-value>
</context-param>

The Initializer class

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.gordondickens.springthreeone.services;
import org.cloudfoundry.runtime.env.CloudEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
public class CloudApplicationContextInitializer implements
  ApplicationContextInitializer<ConfigurableApplicationContext> {
     
  private static final Logger logger = LoggerFactory
    .getLogger(CloudApplicationContextInitializer.class);
  @Override
  public void initialize(ConfigurableApplicationContext applicationContext) {
    CloudEnvironment env = new CloudEnvironment();
    if (env.getInstanceInfo() != null) {
      logger.info("Application running in cloud. API '{}'",
        env.getCloudApiUri());
      applicationContext.getEnvironment().setActiveProfiles("cloud");
      applicationContext.refresh();
    } else {
      logger.info("Application running local");
      applicationContext.getEnvironment().setActiveProfiles("dev");
    }
  }
}

Annotation Support for JavaConfig

If we are are using JavaConfig to define our beans, Spring 3.1 includes the @Profileannotation for enabling bean config files by profile(s).

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.gordondickens.springthreeone.configuration;
import com.gordondickens.springthreeone.SimpleBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("dev")
public class AppConfig {
  @Bean
  public SimpleBean simpleBean() {
    SimpleBean simpleBean = new SimpleBean();
    simpleBean.setMyString("Ripped Pants");
    return simpleBean;
  }
}

Testing with XML Configuration

With XML configuration we can simply add the annotation @ActiveProfiles to the JUnit test class. To include multiple profiles, use the format @ActiveProfiles(profiles = {"dev", "prod"})

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.gordondickens.springthreeone;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ActiveProfiles(profiles = "dev")
public class DevBeansTest {
  @Autowired
  ApplicationContext applicationContext;
  @Test
  public void testDevBeans() {
    SimpleBean simpleBean =
      applicationContext.getBean("constructorBean", SimpleBean.class);
    assertNotNull(simpleBean);
  }
  @Test(expected = NoSuchBeanDefinitionException.class)
  public void testProdBean() {
    SimpleBean prodBean = applicationContext.getBean("prodBean", SimpleBean.class);
    assertNull(prodBean);
  }
}

Testing with JavaConfig

JavaConfig allows us to configure Spring with or without XML configuration. If we want to test beans that are defined in a Configuration class we configure our test with the loaderand classes arguments of the @ContextConfiguration annotation.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.gordondickens.springthreeone.configuration;
import com.gordondickens.springthreeone.SimpleBean;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles(profiles = "dev")
public class BeanConfigTest {
  @Autowired
  SimpleBean simpleBean;
  @Test
  public void testBeanAvailablity() {
    assertNotNull(simpleBean);
  }
}

Declarative Configuration in WEB.XML

If we desire to set the configuration in WEB.XML, this can be done with parameters onContextLoaderListener.

Application Context

?
1
2
3
4
5
6
7
8
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/app-config.xml</param-value>
</context-param>
<context-param>
  <param-name>spring.profiles.active</param-name>
  <param-value>DOUBLEUPMINT</param-value>
</context-param>

Log Results

DEBUG PropertySourcesPropertyResolver - Found key 'spring.profiles.active' in [servletContextInitParams] with type [String] and value 'DOUBLEUPMINT'

Environment Variable/JVM Parameter
Setting an environment variable can be done with either spring_profiles_default orspring_profiles_active. In Unix/Mac it would be export SPRING_PROFILES_DEFAULT=DEVELOPMENT for my local system.

We can also use the JVM “-D” parameter which also works with Maven when using Tomcat or Jetty plugins.

Note: Remember the tokens are NOT case sensitive and can use periods or underscores as separators. For Unix systems, you need to use the underscore, as above.

Logging of system level properties DEBUG PropertySourcesPropertyResolver - Found key 'spring.profiles.default' in [systemProperties] with type [String] and value 'dev,default'

Summary

Now we are equipped to activate various Spring bean sets, based on profiles we define. We can use  traditional, XML based configuration, or the features added to support JavaConfig originally introduced in Spring 3.0.

转载于:https://www.cnblogs.com/davidwang456/p/4429058.html

Spring 3.1 Environment Profiles--转载相关推荐

  1. Spring中Environment详解,一文搞透Spring运行环境Environment

    文章目录 一.理解 Spring Environment 抽象 1.源码初识 二.Environment 占位符处理 1.Spring 3.1 前占位符处理 2.Spring 3.1 + 占位符处理 ...

  2. Spring AOP详解(转载)所需要的包

    上一篇文章中,<Spring Aop详解(转载)>里的代码都可以运行,只是包比较多,中间缺少了几个相应的包,根据报错,几经百度搜索,终于补全了所有包. 截图如下: 在主测试类里面,有人怀疑 ...

  3. Spring 中JCA CCI分析--转载

    转载地址:http://blog.csdn.net/a154832918/article/details/6790612 J2EE提供JCA(Java Connector Architecture)规 ...

  4. Spring Boot详细学习地址转载

    阿里中间件牛人,学习榜样,源码分析: https://fangjian0423.github.io/ 基础.详细.全面的教程: https://gitee.com/roncoocom/spring-b ...

  5. spring各jar包作用(转载)

    除了spring.jar文件,Spring还包括有其它13个独立的jar包,各自包含着对应的Spring组件,用户可以根据自己的需要来选择组合自己的jar包,而不必引入整个spring.jar的所有类 ...

  6. spring boot + maven使用profiles进行环境隔离

    Spring Profile Spring可使用Profile决定程序在不同环境下执行情况,包含配置.加载Bean.依赖等. Spring的Profile一般项目包含:dev(开发), test(单元 ...

  7. Spring Cloud底层原理(转载 石杉的架构笔记)

    拜托!面试请不要再问我Spring Cloud底层原理 原创: 中华石杉 石杉的架构笔记 目录 一.业务场景介绍 二.Spring Cloud核心组件:Eureka 三.Spring Cloud核心组 ...

  8. RESTful Web Services in Spring 3(下)转载

    上一篇我主要发了RESTful Web Services in Spring 3的服务端代码,这里我准备写客户端的代码. 上篇得连接地址为:http://yangjizhong.iteye.com/b ...

  9. spring依赖注入原理(转载)

    关于spring依赖注入原理的文章在网络上已经有很多,我要写的这篇文章原文出自http://taeky.iteye.com/blog/563450,只所以再一次写下来只是为了一为自己收藏,方便以后的复 ...

最新文章

  1. Spring Boot 整合 Netty(附源码)
  2. window下pip 用不了的一种解决办法
  3. 文件行数_linux/unix下如何统计文件行数
  4. Egret中使用P2物理引擎
  5. Django基础11(Django中form表单)
  6. log4j 写入信息到文件简单举例
  7. 洛谷 [P1387] 最大正方形
  8. windows 域名+虚拟目录 (php)
  9. cdev 结构体、设备号相关知识解析
  10. 使用visual studio code 编写小程序代码
  11. 游吟诗人之中二病犯了
  12. VI的简单配置及配置文件集锦 z
  13. 应Oracle BEA定下每股21美元收购价
  14. 作业录屏+露脸+视频裁剪+字幕添加(支持双语)
  15. 四个参数秒懂巴菲特价值投资
  16. 牛客OR36 .链表的回文结构
  17. 台式计算机内存可以扩展到多大,64位电脑系统可以支持多大内存【详细介绍】...
  18. String[]数组初始化
  19. 代码整洁之道(上篇)
  20. 多变量时序响应函数工具箱:一个用于关联神经信号与连续刺激的MATLAB的工具箱

热门文章

  1. 图像重建算法_降噪重建技术路在何方?
  2. python如何下载tushare_安装tushare
  3. java求一个数的阶乘_Java如何使用方法计算一个数字的阶乘值?
  4. java oss 断点上传文件_java实现oss断点续传
  5. python进行数据分析,学习笔记 第8章(1)
  6. c语言两个程序合并一起运行,这两个程序如何可以在一起运行
  7. linux系统硬盘坏道,如何在 Linux 系统下检测硬盘上的坏道和坏块
  8. tf.argsort
  9. ubuntu 安装 postgres
  10. python 正则学习笔记