`
bellicism
  • 浏览: 15513 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

spring 3.1 Enviroment

阅读更多

 

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"?>
       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
 
    <bean id="businessService"
       class="com.c...s.springthreeone.business.SimpleBusinessServiceImpl"/>
 
    <beans profile="dev,qa">
        <bean id="constructorBean"
          class="com.chariotsolutions.springthreeone.SimpleBean"
              c:myString="Constructor Set"/>
 
        <bean id="setterBean"
          class="com.chariotsolutions.springthreeone.SimpleBean">
            <property name="myString" value="Setter Set"/>
        </bean>
    </beans>
 
    <beans profile="prod">
        <bean id="setterBean"
          class="com.chariotsolutions.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 exceptionorg.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.chariotsolutions.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.chariotsolutions.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 @Profile annotation 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.chariotsolutions.springthreeone.configuration;
 
import com.chariotsolutions.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.chariotsolutions.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 loader and 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.chariotsolutions.springthreeone.configuration;
 
import com.chariotsolutions.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.

 

来源:http://blog.chariotsolutions.com/2012/01/spring-31-cool-new-features.html

参考Spring官方文档:http://blog.springsource.org/2011/02/11/spring-framework-3-1-m1-released/

分享到:
评论

相关推荐

    Enviro - Dynamic Enviroment.zip

    Enviro - Dynamic Environment 是一款专为Unity开发设计的环境插件,它提供了丰富的环境设置功能,使得游戏开发者能够轻松创建出各种逼真的天气效果。这款插件的核心特性在于其高度的灵活性和可定制性,允许用户在...

    build_enviroment.tar.xz

    build_enviroment.tar.xz

    Laravel开发-local-enviroment

    "Laravel开发-local-enviroment" 提供了一种便捷的方法来创建和管理本地开发环境,使得开发者可以在自己的机器上搭建与生产环境相似的环境,确保代码在本地测试时的稳定性和兼容性。下面我们将深入探讨这个主题。 1...

    OpenGL_Tutorial_Enviroment.zip

    该资源包"OpenGL_Tutorial_Enviroment.zip"包含了一个基于Visual Studio 2019的完整工程,确保用户可以快速启动并运行OpenGL项目。以下是对该资源包中的主要组件的详细说明: 1. **assimp.lib**:Assimp是一个开源...

    JAVA_SET_enviroment

    标题“JAVA_SET_enviroment”暗示了我们讨论的主题与设置Java开发环境有关,特别是关于配置Java环境变量的步骤。在编程领域,尤其是Java开发中,正确地设置环境变量是至关重要的,因为它们指定了系统如何找到并执行...

    商务智能教学课件:I Operational Data Enviroment and Assignment 1.ppt

    商务智能教学课件:I Operational Data Enviroment and Assignment 1.ppt

    Bluetooth enviroment monitor.rar_DA14580上的环境监测程序_sensors_传感器_光敏传

    标题中的“Bluetooth enviroment monitor.rar”表明这是一个与蓝牙相关的环境监测程序,它可能是通过蓝牙技术来收集和传输数据的。DA14580是一个智能蓝牙微控制器,由Dialog Semiconductor公司生产,常用于低功耗...

    SFL Java Trading System Enviroment

    一个国外公司开发的金融交易系统开源项目,java语言,纯英文环境

    Accurate 3-d posotion in indoor enviroment

    Position and orientation of indoor mobile robots must be obtained real timely during operation in structured industrial environment, so as to ensure the security and efficiency of cargo transportation...

    Building energy and enviroment design application manual

    根据提供的文件信息,我们可以归纳出以下相关知识点: ### 建筑能源与环境设计应用手册 #### 一、概述 《建筑能源与环境设计应用手册》(Building Energy and Environment Design Application Manual)是一本由...

    Introduction to the Matlab Programming Enviroment.pdf

    MATLAB,全称为矩阵实验室(Matrix Laboratory),是一个强大的交互式编程环境,专为解决各种计算问题而设计。从处理传感器的原始数据到物理应用,如计算流体力学(CFD)和有限元方法(FEM),再到数据可视化,如...

    Unity Trees Grass & Rocks Enviroment Pack v1.0

    这个完整的环境包是你一直在寻找的创造你的自然环境包包括树木,大岩石,岩石,小岩石,草,灌木,蕨类植物等… 所有纹理均为TARGA和PNG格式,分辨率为256/512/1024/2048/4096。型号10~20000 Tris之间的Polycount...

    SUSE Linux系列-Vmware Enviroment .ppt

    Vmware 环境下构造Suse Linux 讲义

    How to build RHEL-4.3 diskiless enviroment

    RHEL-4.3环境下(当然也可用于其它红帽系统,如Fedora)创建无盘工作站的方法,虽然是英文的,但是还看得懂。

    Research on Visualization of Electromagnetic Enviroment over Complex Terrain

    Visualization of electromagnetic environment over complex terrain is the current development trend of visualization of electromagnetic situation. Visualization of electromagnetic environment ...

    Use Node.js as a full cloud enviroment development stack

    ### 使用Node.js作为完整的云端开发环境 随着技术的飞速发展与创新,新的想法和技术不断涌现,其中Server-side JavaScript就是一种极具潜力的概念。Node.js作为一种为版本8 JavaScript引擎设计的事件驱动I/O框架,...

    advance programming in unix enviroment 2e and its code

    《Advanced Programming in the UNIX Environment, 2nd Edition》(APUE 2E)是一本经典的UNIX系统编程指南,由Stephen R. Wallace和W. Richard Stevens合著。这本书深入讲解了在UNIX环境中进行高级程序设计的各种...

    jdk1.5-jar package

    **描述:“jdk1.5-the enviroment of java developing”** 描述中提到的“Java开发环境”是指一套完整的工具和配置,使得开发者能够在计算机上编写、编译、调试和运行Java代码。JDK 1.5,也称为Java 5.0,是Oracle...

    Anaconda conda 不能用,一直Solving enviroment 最后报错CondaHTTPError: HTTP 000 CONNECTION FAILED for url

    Solving enviroment \ 一直转圈圈,不能完成。上网搜索了一大圈方法,于是尝试: conda update conda  还是转圈圈,不过转了一会出现了以下提示: CondaHTTPError: HTTP 000 CONNECTION FAILED for url Elapsed: ...

    React_enviroment_tutorial

    React_enviroment_tutorial是一个教程,旨在帮助开发者了解如何配置和管理React开发环境。 首先,我们需要理解React的基础。React是由Facebook开发的开源库,它允许我们使用组件化的方式来构建UI。React通过虚拟DOM...

Global site tag (gtag.js) - Google Analytics