Environment
环境在容器中是一个抽象的集合,是指应用环境的2个方面: profiles和 properties.

profile
配置是一个被命名的,bean定义的逻辑组,这些bean只有在给定的profile配置激活时才会注册到容器。不管是XML还是注解,Beans都有可能指派给profile配置。Environment环境对象的作用,对于profiles配置来说,它能决定当前激活的是哪个profile配置,和哪个profile是默认。

在所有的应用中,Properties属性扮演一个非常重要的角色,可能来源于一下源码变量:properties文件,JVM properties,system环境变量,JNDI, servlet context parameters上下文参数,专门的Properties对象,Maps等等。Environment对象的作用,对于properties来说,是提供给用户方便的服务接口,方便撰写配置、方便解析配置。

bean定义profiles是核心容器内的一种机制,该机制能在不同环境中注册不同的bean。环境的意思是,为不同的用户做不同的事儿,该功能在很多场景中都非常有用,包括:开发期使用内存数据源,在QA或者产品上则使用来自JNDI的相同的数据源开发期使用监控组件,当部署以后则关闭监控组件,是应用更高效为用户各自注册自定义bean实现.

考虑一个实际应用中的场景,现在需要一个DataSource。开测试环境中,这样配置:

@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("my-schema.sql")
.addScript("my-test-data.sql")
.build();
}

  

现在想一想,如何将应用部署到QA或者生产环境,假设生产环境中使用的JNDI。我们的dataSource bean看起来像这样:

@Bean(destroyMethod="")
public DataSource dataSource() throws Exception {
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
}

  

我们需要在某些上下文环境中使用某些bean,在其他环境中则不用这些bean。你也许会说,你需要在场景A中注册一组bean定义,在场景B中注册另外一组。先看看我们如何修改配置来完成此需求。
@Profile注解的作用,是在一个或者多个指定profiles激活的情况下,注册某个组件。使用上面的样例,重写dataSource配置:

@Configuration
@Profile("dev")
public class StandaloneDataConfig { @Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.addScript("classpath:com/bank/config/sql/test-data.sql")
.build();
}
}
@Configuration
@Profile("production")
public class JndiDataConfig { @Bean(destroyMethod="")
public DataSource dataSource() throws Exception {
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
}
}

  

开启profile

要修改配置,我们仍然需要指定要激活哪个文件。如果现在运行上面的样例应用,它会抛异常NoSuchBeanDefinitionException,因为容器找不到dataSourcebean。

有多种方式激活配置,但是最直接的方式是编程式的方式使用ApplicationContext API

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("dev");
ctx.register(SomeConfig.class, StandaloneDataConfig.class, JndiDataConfig.class);
ctx.refresh();

  

此外,还可以使用spring.profiles.active激活配置,该属性可以配置在系统环境变量、JVM系统属性、web.xml
中JNDI中的servlet context上下文参数
注意配置文件不是单选;可能会同时激活多个配置文件,编程式的使用方法setActiveProfiles(),该方法接收String数组参数,也就是多个配置文件名

ctx.getEnvironment().setActiveProfiles("profile1", "profile2");
//声明式的使用spring.profiles.active ,值可以为逗号分隔的配置文件名列表, -Dspring.profiles.active="profile1,profile2"

 

如果没有任何profile配置被激活,默认的profile将会激活。
默认profile配置文件可以更改,通过环境变量的setDefaultProfiles方法,或者是声明的spring.profiles.default属性值

Spring的环境抽象提供了用于检索一系列的property sources属性配置文件。

ApplicationContext ctx = new GenericApplicationContext();
Environment env = ctx.getEnvironment();
boolean containsFoo = env.containsProperty("foo");
System.out.println("Does my environment contain the ''foo'' property? " + containsFoo);

  

在上面的片段中,通过较高层次方式检索SPring是否在当前环境中定义了foo property属性。为了检索该属性,环境对象在一组PropertySource对象中执行检索。PropertySource是key-value键值对配置文件的抽象,Spring的StandardEnvironment
配置了2个PropertySource对象.其一是JVM系统properties(System.getProperties()),另一个是一组系统环境变量System.getEnv()。

@PropertySource注解提供了一个方便的方式,用于增加一个PropertySource到Spring的环境中: 给定一个文件"app.properties"包含了key/value键值对testbean.name=myTestBean,下面的@Configuration类使用了@PropertySource
,使用这种方式调用testBean.getName()将会返回myTestBean。

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
@Autowired
Environment env; @Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}

  

转自:https://www.jianshu.com/p/49e950b0b008

spring Environment的更多相关文章

  1. Spring Environment(一)API 介绍

    Spring Environment(一)API 使用 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring 3. ...

  2. Spring Environment(二)源码分析

    Spring Environment(二)源码分析 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Envi ...

  3. Spring Environment(三)生命周期

    Spring Environment(三)生命周期 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Envi ...

  4. Spring Environment抽象

    1:概述 Spring中Environment是Spring3.1版本引入的,是Spring核心框架定义的一个接口,用来表示整个应用运行时环境.该环境模型只接受两种应用环境profiles(配置文件) ...

  5. Spring Environment的加载

     这节介绍environment,默认环境变量的加载以及初始化.  之前在介绍spring启动过程讲到,第一步进行环境准备时就会初始化一个StandardEnvironment.下图为Environm ...

  6. Spring Environment对象获取属性

    String[] activeProfiles = env.getActiveProfiles();//获取当前是启用哪一个个配置文件 System.out.println(Arrays.toStri ...

  7. Spring中的Environment外部化配置管理详解

    Environment的中文意思是环境,它表示整个spring应用运行时的环境信息,它包含两个关键因素 profiles properties profiles profiles这个概念相信大家都已经 ...

  8. 【译】Spring 4 @PropertySource和@Value注解示例

    前言 译文链接:http://websystique.com/spring/spring-propertysource-value-annotations-example/ 本篇文章将展示如何通过@P ...

  9. spring configuration 注解

    org.springframework.context.annotation @annotation.Target({ElementType.TYPE}) @annotation.Retention( ...

随机推荐

  1. Android Material Design控件使用(二)——FloatButton TextInputEditText TextInputLayout 按钮和输入框

    FloatingActionButton 1. 使用FloatingActionButton的情形 FAB代表一个App或一个页面中最主要的操作,如果一个App的每个页面都有FAB,则通常表示该App ...

  2. 大家好,又是新的一天。今天给大家带来一些新的知识:选择器的种类和css的三种样式

    今天我们为大家 选择了 六种 选择器: 1. 标签选择器 2.id选择器 3.class选择器 4.后代选择器 5.子代选择器 6.交集选择器 我们就举三个典型的例子:后代选择器,子代选择器和交集选择 ...

  3. Mybatis框架可视化(1)

    Mybatis整体架构视图: 接 口 层 SqlSession (定义了Mybatis暴露给应用程序调用的API) 核 心 处 理 层 配置解析 (加载核心配置.映射配置. mapper接口注解信息, ...

  4. js 面向对象 ES5 AND ES6

    1. ES5实现 父类: // 职员类 function Employees(id,name,salary) { // 属性 this.id = id; this.name = name; this. ...

  5. 1970年// iPhone “变砖”后可继续正常使用的解决方案

    0.解决方案 说话先说重点,“变砖”后的iphone怎么正常使用. 拆开后盖,给电源和处理器之间断下电就OK了. 1.事件来源 对于iPhone和iPad,把时间手动设置到1970年5月以前会出现“变 ...

  6. OkHttp3源码详解(六) Okhttp任务队列工作原理

    1 概述 1.1 引言 android完成非阻塞式的异步请求的时候都是通过启动子线程的方式来解决,子线程执行完任务的之后通过handler的方式来和主线程来完成通信.无限制的创建线程,会给系统带来大量 ...

  7. tkinter——GUI设计实操

    1.创建root: from tkinter import * root = Tk() root.title('GUI设计') # root.attributes("-alpha" ...

  8. HDU 1086

    You can Solve a Geometry Problem too Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/3 ...

  9. PHP的匿名函数和闭包

    匿名函数 // Example1 $func = function( $param ) { echo $param; }; $func( 'some string' );//输出:some strin ...

  10. C#-非泛型集合的方法

    非泛型集合的类和接口位于System.Collections命名空间 如:列表.队列.位数组.哈希表和字典的集合     ArrayList 动态数组 可被单独索引的对象的有序集合可以使用索引在指定的 ...