spring中的环境Enviroment

上周清明节在家没事看了一会spring的源码。主要是spring-core中的env模块。

spring运行的环境主要包含两个方面,一个是环境中设置的属性信息,一个是profile。

属性信息就是通过application.properties或者通过命令行启动时候用–attr=value启动的一些参数。

profile表示环境中哪些bean是当前进程加载的。(我一般用profile来配置测试/开发/预发/生产环境)。

这个模块中最基本的一个抽象类是PropertySource,一个嘴基本的接口是PropertyResolver。

PropertySource是属性的载体,而PropertyResolver是对PropertySource使用工具。两者组合完成了所有对属性的解析,包括对${}占位符的自动解析。

Enviroment在继承PropertyResolver的同时,还增加了对Profile的管理。Enviroment是ApplicationContext中很重要的一部分。

一下是我对这几个类或借口的理解

  • PropertySource:属性集合。比如可以代表名称为systemProperties 的系统自带属性集合。

  • EnumerablePropertySource:封装了PropertySource的使用,通过一个getPropertyNames方法获取所有的属性名的方式来使用。

  • MapPropertySource:一个真实可用的PropertySource,只不过规定PropertySource的source必须是Map类型。
  • PropertiesPropertySource:继承MapPropertySource,规定source必须是Properties类型。
  • SystemEnvironmentPropertySource:这是MapPropertySource的一种特殊实现,专门用于配置Enviroment,这个类增加了shell环境中对一些特殊符号的兼容。
  • CommandLinePropertySource:比较普通,抽象了通过命令行设置的属性源,包含了option arguments和non-option arguments。
  • SimpleCommandLinePropertySource:CommandLinePropertySource的一个简单实现。
  • CommandLineArgs:命令行参数的抽象。
  • SimpleCommandLineArgsParser:命令行参数解析器。
  • CompositePropertySource:组合属性源,可以把多个propertySource组合成一个属性源来使用。
  • PropertySources:多个PropertySource组合在一起,但不是PropertySource。
  • MutablePropertySources:PropertySources的默认实现。
  • PropertyResolver:属性解析器借口。包括属性的获取和占位符的解析。
  • ConfigurablePropertyResolver:可配置的属性解析器,允许配置属性占位符的分隔符和前缀后缀,也能配置属性类型转换器。
  • AbstractPropertyResolver:属性解析器的抽象实现,没什么特殊的。
  • MissingRequiredPropertiesException:必要属性的不存在时抛的异常。
  • PropertyPlaceholderHelper:解析属性占位符的具体算法。
  • PropertySourcesPropertyResolver:PropertyResolver的唯一一个实现。
  • Environment:在PropertyResolver的基础上加上了获取profile相关的操作。
  • ConfigurableEnvironment:增加了设置profile的操作。
  • AbstractEnvironment:Enviroment的抽象基类。实现了一些简单的操作profile和propertySource的接口。
  • StandardEnvironment:标准环境类,在抽象基类的基础上修改了增加MapPropertySource和SystemEnvironmentPropertySource的行为。
  • EnvironmentCapable:只定义了一个接口用于获取环境对象。
  • ReadOnlySystemAttributesMap:只读属性。其实只是个readonly的map。