Environment 接口介绍

在 Spring 中,Environment 接口主要管理应用程序两个方面的内容:profile 和 properties。

profile 可以简单的等同于环境,比如说平时项目中常见的环境有开发(dev)、测试(stg)和生产(prod),Spring 启动的时候可以设置激活具体的环境。当然,这个 profile 我们还可以为其赋予很多含义,这个主要看你的业务。比如说,你开发的软件会交付给客户A,也会交付给客户B,那么这个 profile 也可以定义成客户的含义

properties 是配置,配置的来源有很多,可以是配置文件、JVM 的参数、系统的环境变量、JNDI、Sevlet Contxet 参数以及 Map 对象等,使用 Environment 接口,可以方便的获取这些配置。

Bean Definition Profiles

使用 @Profile

Spring 容器可以根据不同的 profile 配置不同的 Bean。这个特性可以帮助你实现很多灵活的功能,比如:

  • 开发环境使用内存数据库,测试和生产环境才使用关系型数据库,比如 Mysql 和 Oracle 等
  • 交互给客户 A 的软件使用 A 特性,交付给客户 B 的软件使用 B 特性
@Configuration
@Profile("development")
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 非常适合在两个环境下,Bean 的定义完全不一样的情况,如果两个 Bean 的定义是一样的,只是一些参数不一样的话,我们完全可以使用配置文件的方式实现。

@Profile 注解后面的表达式可以是一个简单的字符串,也可以是一个逻辑运算符。@Profile 支持如下的逻辑运算符。

  • !: A logical “not” of the profile
  • &: A logical “and” of the profiles
  • |: A logical “or” of the profiles

说明:

If a @Configuration class is marked with @Profile, all of the @Bean methods and @Import annotations associated with that class are bypassed unless one or more of the specified profiles are active. If a @Component or @Configuration class is marked with @Profile({"p1", "p2"}), that class is not registered or processed unless profiles 'p1' or 'p2' have been activated.

使用 xml 方式配置

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="..."> <!-- other bean definitions --> <beans profile="development">
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
<jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
</jdbc:embedded-database>
</beans> <beans profile="production">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
</beans>
</beans>

激活 profile

1. API 方式

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
// 设置激活的 profile
ctx.getEnvironment().setActiveProfiles("development");
ctx.register(SomeConfig.class, StandaloneDataConfig.class, JndiDataConfig.class);
ctx.refresh();

2. 命令行方式

-Dspring.profiles.active="profile1,profile2"

3. 配置文件方式

spring:
profiles:
active: dev

默认的 profile

Spring 默认的 profile 是 default,可以通过 Environment 的 API 进行修改。

PropertySource 接口

PropertySource 接口是对任何形式的 key-value 键值对的抽象。

@PropertySource

@PropertySource 这个注解的作用是将配置文件中的键值对放入Environment。这个注解的作用和传统配置方式中的 context:place-hold一致。

@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;
}
}

经过上面这样的配置,我们就可以使用 ${key} 这种形式来取变量的值。有时如果我们没配置 key 的值,Spring 会抛异常。这时我们可以使用 ${key:defaultvalue} 这种形式配置默认值

Spring系列.Environment接口的更多相关文章

  1. Spring系列.Resource接口

    接口简介 JDK中提供了java.net.URL这个类来用于获取不同种类的资源(根据不同前缀的url可以获取不同种类的资源).但是URL这个类没有获取classpath和ServletContext下 ...

  2. Spring系列15:Environment抽象

    本文内容 Environment抽象的2个重要概念 @Profile 的使用 @PropertySource 的使用 Environment抽象的2个重要概念 Environment 接口表示当前应用 ...

  3. Spring系列(零) Spring Framework 文档中文翻译

    Spring 框架文档(核心篇1和2) Version 5.1.3.RELEASE 最新的, 更新的笔记, 支持的版本和其他主题,独立的发布版本等, 是在Github Wiki 项目维护的. 总览 历 ...

  4. Spring 系列目录

    Spring(https://spring.io/) 系列目录 第一篇:Spring 系列 第一章 Spring Core (1) Convert 1.1.1 Spring ConversionSer ...

  5. 深入理解Spring系列之七:web应用自动装配Spring配置

    转载 https://mp.weixin.qq.com/s/Lf4akWFmcyn9ZVGUYNi0Lw 在<深入理解Spring系列之一:开篇>的示例代码中使用如下方式去加载Spring ...

  6. 深入理解Spring系列之五:BeanDefinition装载

    转载 https://mp.weixin.qq.com/s/1_grvpJYe8mMIAnebMdz9Q 接上篇<深入理解Spring系列之四:BeanDefinition装载前奏曲>,进 ...

  7. Spring系列(三):Spring IoC源码解析

    一.Spring容器类继承图 二.容器前期准备 IoC源码解析入口: /** * @desc: ioc原理解析 启动 * @author: toby * @date: 2019/7/22 22:20 ...

  8. Spring系列14:IoC容器的扩展点

    Spring系列14:IoC容器的扩展点 回顾 知识需要成体系地学习,本系列文章前后有关联,建议按照顺序阅读.上一篇我们详细介绍了Spring Bean的生命周期和丰富的扩展点,没有阅读的强烈建议先阅 ...

  9. Spring 系列: Spring 框架简介 -7个部分

    Spring 系列: Spring 框架简介 Spring AOP 和 IOC 容器入门 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级 ...

随机推荐

  1. 偷天换日 树形DP+背包

    A. 偷天换日 内存限制:256 MiB 时间限制:1000 ms 标准输入输出 题目类型:传统 评测方式:文本比较   题目描述 神偷对艺术馆内的名画垂涎欲滴准备大捞一把.艺术馆由若干个展览厅和若干 ...

  2. noip模拟32[好数学啊]

    noip模拟32 solutions 真是无语子,又没上100,无奈死了 虽然我每次都觉得题很难,但是还是有好多上100的 战神都200多了,好生气啊啊啊 从题开始变难之后,我的时间分配越来越不均匀, ...

  3. Elgamal加密算法和数字签名

    简述:ElGamal公钥密码体制是由 T.ElGamal于 1985年提出的,直到现在仍然是一个安全性能良好的公钥密码体制.该算法既能用于数据加密也能用于数字签名,其安全性依赖于计算有限域上离散对数这 ...

  4. 防火墙和SElinux简单配置

    1.查看防火墙状态 # firewall-cmd --state          &    #systemctl status  firewalld.service 2.停止与开启firew ...

  5. Flutter开发进阶学习指南Flutter开发进阶学习指南

    Flutter 的起源 Flutter 的诞生其实比较有意思,Flutter 诞生于 Chrome 团队的一场内部实验, 谷歌的前端团队在把前端一些"乱七八糟"的规范去掉后,发现在 ...

  6. 1.9 货仓选址问题——Python

    题目描述 在一条数轴上有 N 家商店,它们的坐标分别为 A1~AN. 现在需要在数轴上建立一家货仓,每天清晨,从货仓到每家商店都要运送一车商品. 为了提高效率,求把货仓建在何处,可以使得货仓到每家商店 ...

  7. 建立局域网内使用的CentOS7源

    建立局域网内使用的CentOS7源 by 无若    1. 在CentOS下建立匿名的FTP访问服务 CentOS 7下安装配置pure-ftpd,并使用匿名用户登录 Pure-FTPd是Linux上 ...

  8. Python--构建发布自己的模块

    参考博客https://www.cnblogs.com/simple-free/p/8283263.html 1.   新建一个模块(名称自定义),存放要发布的模块代码. 2.   新建一个setup ...

  9. 官宣 .NET 6 预览版 6

    我们很高兴宣布.NET 6 预览版6问世啦.预览版6 是我们RC版发布之前的倒数第二个预览版. 我们将有两个RC版. 此版本本身相对较小,而预览版7会更大. 在那之后,我们将进行质量修复,直到11 月 ...

  10. 06-SpringCloud Eureka

    Eureka基础知识 什么是服务治理 Spring Cloud封装了Netflix 公司开发的Eureka模块来实现服务治理 在传统的RPC远程调用框架中,管理每个服务与服务之间依赖关系比较复杂,管理 ...