b spring 之profile & environment 环境配置 & 启动时修改类字节码

13 环境的抽象

容器中集成了抽象的环境接口Environment,用来对两个关键起作用:profilesproperties
profile是对一堆bean配置的逻辑分类。Bean会被绑定到一个profile中去。Environment对象与profile管理,确定哪个profile会被最终使用。

properties在几乎所有应用程序中都起着重要作用,并且可能源自各种来源:属性文件,JVM系统属性,系统环境变量,JNDI,Servlet上下文参数,临时属性对象,Map对象等。环境对象与属性有关的作用是为用户提供方便的服务界面,用于配置属性源并从中解析属性。

13.1 Bean 定义的Profiles

Bean 定义 Profile文件可以提供一个构建mechanism在核心容器,用来在不同环境里定义不同的Bean。

  • 在开发中针对内存中的数据源进行工作,而不是在进行QA或生产时从JNDI查找相同的数据源。
  • 仅在将应用程序部署到演示环境中时注册基础设施。
  • 注册自定义的bean的时候

演示:手动编码
考虑以下数据源的创建
b spring 之profile & environment 环境配置 & 启动时修改类字节码
现在考虑应用如何被部署到QA环境或者生产环境。假定数据源和JDNI目录一同注册。所以如下手动的去配置属性文件
b spring 之profile & environment 环境配置 & 启动时修改类字节码
考虑一下如何切换的问题,之前以xml的方式用${placeholder}的来切换。

使用@Profile

类级别

@Profile注解让你指定具体componment会被注册
development的source
b spring 之profile & environment 环境配置 & 启动时修改类字节码
正式的JNDI的source
b spring 之profile & environment 环境配置 & 启动时修改类字节码

方法级别

b spring 之profile & environment 环境配置 & 启动时修改类字节码

利用@Profile写注解

b spring 之profile & environment 环境配置 & 启动时修改类字节码

xml profile配置

定义
b spring 之profile & environment 环境配置 & 启动时修改类字节码
使用
b spring 之profile & environment 环境配置 & 启动时修改类字节码

**Profile

启动时要明确具体的Profile。同时找不到bean定义时会抛出NoSuchBeanDefinitionException
**profile的方式有好几种,但是最直接的方式编码式

编码**

b spring 之profile & environment 环境配置 & 启动时修改类字节码
你也可以通过spring.profiles.active属性来选择。
集成测试中通过使用 @ActiveProfiles注解来指明
也可以声明多个Profile文件
b spring 之profile & environment 环境配置 & 启动时修改类字节码

java启动参数-D 变量

b spring 之profile & environment 环境配置 & 启动时修改类字节码

默认的profile

b spring 之profile & environment 环境配置 & 启动时修改类字节码
也可以通过setDefaultProfiles()或者spring.profiles.default

13.2 PropertySource Abstraction

Environment是对环境的抽象,思考下面的问题
b spring 之profile & environment 环境配置 & 启动时修改类字节码
这个例子是查询环境变量中,有没有my-property的属性。
Spring的Environment 会从一堆PropertySource中查找。
Spring标准的PropertySource只有两个:jvm实例变量(System.getProperties())和系统ENV变量(System.getenv())

优先从System.getProperties()中找
对于标准的StandardServletEnvironment查找顺序为
b spring 之profile & environment 环境配置 & 启动时修改类字节码

一个自定义的数据源添加
b spring 之profile & environment 环境配置 & 启动时修改类字节码

13.3 数据源注解

配置数据源,如下,会被注入到Envirment env中去
b spring 之profile & environment 环境配置 & 启动时修改类字节码
${…}表达式
b spring 之profile & environment 环境配置 & 启动时修改类字节码

13.4 placeholer式声明

从历史上看,placeholer的值只能根据JVM系统属性或环境变量来解析。这已不再是这种情况。由于环境抽象是在整个容器中集成的,因此很容易通过placeholer的解析。这意味着您可以按照自己喜欢的任何方式配置解析过程。您可以更改搜索系统属性和环境变量的优先级,也可以完全删除它们。您还可以根据需要将自己的属性源添加到组合中。
b spring 之profile & environment 环境配置 & 启动时修改类字节码

14.Registering a LoadTimeWeave

Spring使用LoadTimeWeaver在将类加载到Java虚拟机(JVM)中时对其进行动态转换。
要启用加载时织入,可以将@EnableLoadTimeWeaving添加到您的@Configuration类之一,如以下示例所示:
b spring 之profile & environment 环境配置 & 启动时修改类字节码
等同于
b spring 之profile & environment 环境配置 & 启动时修改类字节码
为ApplicationContext配置后,该ApplicationContext中的任何bean都可以实现LoadTimeWeaverAware,从而接收到对加载时间weaver实例的引用。与Spring的JPA支持结合使用时,该功能特别有用,因为在JPA类转换中可能需要进行加载时编织。有关更多详细信息,请查阅LocalContainerEntityManagerManagerBean javadoc。有关AspectJ加载时编织的更多信息,请参见Spring框架中的AspectJ加载时编织。