【Spring】——环境 & 属性:PropertySource、Environment、Profile

2020-12-05 · 芋道源码 · 转载 · · 本文共 1,969个字,预计阅读需要 7分钟。

转载于【芋道源码

本文主要基于 Spring 5.0.6.RELEASE

spring.profiles.active@Profile 这两个我相信各位都熟悉吧,主要功能是可以实现不同环境下(开发、测试、生产)参数配置的切换。其实关于环境的切换,小编在博客 【死磕Spring】—— IoC 之 PropertyPlaceholderConfigurer 的应用 中,已经介绍了利用 PropertyPlaceholderConfigurer 来实现动态切换配置环境,当然这种方法需要我们自己实现,有点儿麻烦。但是对于这种非常实际的需求,Spring 怎么可能没有提供呢?下面小编就问题来对 Spring 的环境 & 属性来做一个分析说明。

1. 概括

Spring 环境 & 属性由四个部分组成:PropertySource、PropertyResolver、Profile 和 Environment。

  • PropertySource:属性,key-value 属性对抽象,用于配置数据。
  • PropertyResolver:属性解析器,用于解析属性配置
  • Profile:剖面,只有激活的剖面的组件/配置才会注册到 Spring 容器,类似于 Spring Boot 中的 profile 。
  • Environment:环境,Profile 和 PropertyResolver 的组合。

下面是整个体系的结构图:

整体类图

下面就针对上面结构图对 Spring 的 Properties & Environment 做一个详细的分析。

2. Properties

2.1 PropertyResolver

属性解析器,用于解析任何基础源的属性的接口

  1. // PropertyResolver.java
  2. public interface PropertyResolver {
  3. // 是否包含某个属性
  4. boolean containsProperty(String key);
  5. // 获取属性值 如果找不到返回null
  6. @Nullable
  7. String getProperty(String key);
  8. // 获取属性值,如果找不到返回默认值
  9. String getProperty(String key, String defaultValue);
  10. // 获取指定类型的属性值,找不到返回null
  11. @Nullable
  12. <T> T getProperty(String key, Class<T> targetType);
  13. // 获取指定类型的属性值,找不到返回默认值
  14. <T> T getProperty(String key, Class<T> targetType, T defaultValue);
  15. // 获取属性值,找不到抛出异常IllegalStateException
  16. String getRequiredProperty(String key) throws IllegalStateException;
  17. // 获取指定类型的属性值,找不到抛出异常IllegalStateException
  18. <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException;
  19. // 替换文本中的占位符(${key})到属性值,找不到不解析
  20. String resolvePlaceholders(String text);
  21. // 替换文本中的占位符(${key})到属性值,找不到抛出异常IllegalArgumentException
  22. String resolveRequiredPlaceholders(String text) throws IllegalArgumentException;
  23. }

从 API 上面我们就知道属性解析器 PropertyResolver 的作用了。下面是一个简单的运用。

  1. PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources);
  2. System.out.println(propertyResolver.getProperty("name"));
  3. System.out.println(propertyResolver.getProperty("name", "chenssy"));
  4. System.out.println(propertyResolver.resolvePlaceholders("my name is ${name}"));

下图是 PropertyResolver 体系结构图:

PropertyResolver 体系结构图

  • ConfigurablePropertyResolver:供属性类型转换的功能
  • AbstractPropertyResolver:解析属性文件的抽象基类
  • PropertySourcesPropertyResolver:PropertyResolver 的实现者,他对一组 PropertySources 提供属性解析服务

2.2 ConfigurablePropertyResolver

提供属性类型转换的功能

通俗点说就是 ConfigurablePropertyResolver 提供属性值类型转换所需要的 ConversionService。代码如下:

  1. // ConfigurablePropertyResolver.java
  2. public interface ConfigurablePropertyResolver extends PropertyResolver {
  3. // 返回执行类型转换时使用的 ConfigurableConversionService
  4. ConfigurableConversionService getConversionService();
  5. // 设置 ConfigurableConversionService
  6. void setConversionService(ConfigurableConversionService conversionService);
  7. // 设置占位符前缀
  8. void setPlaceholderPrefix(String placeholderPrefix);
  9. // 设置占位符后缀
  10. void setPlaceholderSuffix(String placeholderSuffix);
  11. // 设置占位符与默认值之间的分隔符
  12. void setValueSeparator(@Nullable String valueSeparator);
  13. // 设置当遇到嵌套在给定属性值内的不可解析的占位符时是否抛出异常
  14. // 当属性值包含不可解析的占位符时,getProperty(String)及其变体的实现必须检查此处设置的值以确定正确的行为。
  15. void setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders);
  16. // 指定必须存在哪些属性,以便由validateRequiredProperties()验证
  17. void setRequiredProperties(String... requiredProperties);
  18. // 验证setRequiredProperties指定的每个属性是否存在并解析为非null值
  19. void validateRequiredProperties() throws MissingRequiredPropertiesException;
  20. }
  • 从 ConfigurablePropertyResolver 所提供的方法来看,除了访问和设置 ConversionService 外,主要还提供了一些解析规则之类的方法。

就 Properties 体系而言,PropertyResolver 定义了访问 Properties 属性值的方法,而 ConfigurablePropertyResolver 则定义了解析 Properties 一些相关的规则和值进行类型转换所需要的 Service。

该体系有两个实现者:AbstractPropertyResolver 和 PropertySourcesPropertyResolver,其中 AbstractPropertyResolver 为实现的抽象基类,PropertySourcesPropertyResolver 为真正的实现者。

2.3 AbstractPropertyResolver

解析属性文件的抽象基类

AbstractPropertyResolver 作为基类它仅仅只是设置了一些解析属性文件所需要配置或者转换器,如 #setConversionService(...)#setPlaceholderPrefix(...)#setValueSeparator(...) 。其实这些方法的实现都比较简单,都是设置或者获取 AbstractPropertyResolver 所提供的属性,代码如下:

  1. // AbstractPropertyResolver.java
  2. // 类型转换去
  3. private volatile ConfigurableConversionService conversionService;
  4. // 占位符
  5. private PropertyPlaceholderHelper nonStrictHelper;
  6. //
  7. private PropertyPlaceholderHelper strictHelper;
  8. // 设置是否抛出异常
  9. private boolean ignoreUnresolvableNestedPlaceholders = false;
  10. // 占位符前缀
  11. private String placeholderPrefix = SystemPropertyUtils.PLACEHOLDER_PREFIX;
  12. // 占位符后缀
  13. private String placeholderSuffix = SystemPropertyUtils.PLACEHOLDER_SUFFIX;
  14. // 与默认值的分割
  15. private String valueSeparator = SystemPropertyUtils.VALUE_SEPARATOR;
  16. // 必须要有的字段值
  17. private final Set<String> requiredProperties = new LinkedHashSet<>();

这些属性都是 ConfigurablePropertyResolver 接口所提供方法需要的属性,他所提供的方法都是设置和读取这些值,如下几个方法:

  1. // AbstractPropertyResolver.java
  2. public ConfigurableConversionService getConversionService() {
  3. // 需要提供独立的DefaultConversionService,而不是PropertySourcesPropertyResolver 使用的共享DefaultConversionService。
  4. ConfigurableConversionService cs = this.conversionService;
  5. if (cs == null) {
  6. synchronized (this) {
  7. cs = this.conversionService;
  8. if (cs == null) {
  9. cs = new DefaultConversionService();
  10. this.conversionService = cs;
  11. }
  12. }
  13. }
  14. return cs;
  15. }
  16. @Override
  17. public void setConversionService(ConfigurableConversionService conversionService) {
  18. Assert.notNull(conversionService, "ConversionService must not be null");
  19. this.conversionService = conversionService;
  20. }
  21. public void setPlaceholderPrefix(String placeholderPrefix) {
  22. Assert.notNull(placeholderPrefix, "'placeholderPrefix' must not be null");
  23. this.placeholderPrefix = placeholderPrefix;
  24. }
  25. public void setPlaceholderSuffix(String placeholderSuffix) {
  26. Assert.notNull(placeholderSuffix, "'placeholderSuffix' must not be null");
  27. this.placeholderSuffix = placeholderSuffix;
  28. }

而对属性的访问,则委托给子类 PropertySourcesPropertyResolver 实现。

  1. // AbstractPropertyResolver.java
  2. public String getProperty(String key) {
  3. return getProperty(key, String.class);
  4. }
  5. public String getProperty(String key, String defaultValue) {
  6. String value = getProperty(key);
  7. return (value != null ? value : defaultValue);
  8. }
  9. public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
  10. T value = getProperty(key, targetType);
  11. return (value != null ? value : defaultValue);
  12. }
  13. public String getRequiredProperty(String key) throws IllegalStateException {
  14. String value = getProperty(key);
  15. if (value == null) {
  16. throw new IllegalStateException("Required key '" + key + "' not found");
  17. }
  18. return value;
  19. }
  20. public <T> T getRequiredProperty(String key, Class<T> valueType) throws IllegalStateException {
  21. T value = getProperty(key, valueType);
  22. if (value == null) {
  23. throw new IllegalStateException("Required key '" + key + "' not found");
  24. }
  25. return value;
  26. }

2.4 PropertySourcesPropertyResolver

PropertyResolver 的实现者,他对一组 PropertySources 提供属性解析服务

它仅有一个成员变量:PropertySources 。该成员变量内部存储着一组 PropertySource,表示 key-value 键值对的源的抽象基类,即一个 PropertySource 对象则是一个 key-value 键值对。PropertySource 的代码如下:

  1. // PropertySource.java
  2. public abstract class PropertySource<T> {
  3. protected final Log logger = LogFactory.getLog(getClass());
  4. protected final String name;
  5. protected final T source;
  6. // ...
  7. }

PropertySourcesPropertyResolver 对外公开的 #getProperty(...) 方法,都是委托给 #getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) 方法实现,他有三个参数,分别表示为:

  • key :获取的 key 。
  • targetValueType : 目标 value 的类型。
  • resolveNestedPlaceholders :是否解决嵌套占位符。

源码如下:

  1. // PropertySourcesPropertyResolver.java
  2. @Nullable
  3. protected <T> T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) {
  4. if (this.propertySources != null) {
  5. // 遍历 propertySources 数组
  6. for (PropertySource<?> propertySource : this.propertySources) {
  7. if (logger.isTraceEnabled()) {
  8. logger.trace("Searching for key '" + key + "' in PropertySource '" +
  9. propertySource.getName() + "'");
  10. }
  11. // 获得 key 对应的 value 值
  12. Object value = propertySource.getProperty(key);
  13. if (value != null) {
  14. // 如果解决嵌套占位符,解析占位符
  15. if (resolveNestedPlaceholders && value instanceof String) {
  16. value = resolveNestedPlaceholders((String) value);
  17. }
  18. // 如果未找到 key 对应的值,则打印日志
  19. logKeyFound(key, propertySource, value);
  20. // value 的类型转换
  21. return convertValueIfNecessary(value, targetValueType);
  22. }
  23. }
  24. }
  25. if (logger.isTraceEnabled()) {
  26. logger.trace("Could not find key '" + key + "' in any property source");
  27. }
  28. return null;
  29. }
  • 首先,从 propertySource 中,获取指定 keyvalue 值。
  • 然后,判断是否需要进行嵌套占位符解析,如果需要则调用 #resolveNestedPlaceholders(String value) 方法,进行嵌套占位符解析。详细解析,见 「2.4.1 resolveNestedPlaceholders」
  • 最后,调用 #convertValueIfNecessary(Object value, Class<T> targetType) 方法,进行类型转换。详细解析,见 「2.4.2 convertValueIfNecessary」

2.4.1 resolveNestedPlaceholders

#resolveNestedPlaceholders(String value) 方法,用于解析给定字符串中的占位符,同时根据 ignoreUnresolvableNestedPlaceholders 的值,来确定是否对不可解析的占位符的处理方法:是忽略还是抛出异常(该值由 #setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders) 方法来设置)。代码如下:

  1. // AbstractPropertyResolver.java
  2. protected String resolveNestedPlaceholders(String value) {
  3. return (this.ignoreUnresolvableNestedPlaceholders ?
  4. resolvePlaceholders(value) : resolveRequiredPlaceholders(value));
  5. }
  • 如果 this.ignoreUnresolvableNestedPlaceholderstrue ,则调用 #resolvePlaceholders(String text) 方法,否则调用 #resolveRequiredPlaceholders(String text) 方法,但是无论是哪个方法,最终都会到 #doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) 方法。该方法接收两个参数:

    1. // AbstractPropertyResolver.java
    2. // String 类型的 text:待解析的字符串
    3. // PropertyPlaceholderHelper 类型的 helper:用于解析占位符的工具类。
    4. private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) {
    5. return helper.replacePlaceholders(text, this::getPropertyAsRawString);
    6. }

PropertyPlaceholderHelper 是用于处理包含占位符值的字符串,构造该实例需要四个参数:

  • placeholderPrefix:占位符前缀。

  • placeholderSuffix:占位符后缀。

  • valueSeparator:占位符变量与关联的默认值之间的分隔符。

  • ignoreUnresolvablePlaceholders:指示是否忽略不可解析的占位符(true)或抛出异常(false)。

  • 构造函数如下:

    1. // PropertyPlaceholderHelper.java
    2. public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix,
    3. @Nullable String valueSeparator, boolean ignoreUnresolvablePlaceholders) {
    4. Assert.notNull(placeholderPrefix, "'placeholderPrefix' must not be null");
    5. Assert.notNull(placeholderSuffix, "'placeholderSuffix' must not be null");
    6. this.placeholderPrefix = placeholderPrefix;
    7. this.placeholderSuffix = placeholderSuffix;
    8. String simplePrefixForSuffix = wellKnownSimplePrefixes.get(this.placeholderSuffix);
    9. if (simplePrefixForSuffix != null && this.placeholderPrefix.endsWith(simplePrefixForSuffix)) {
    10. this.simplePrefix = simplePrefixForSuffix;
    11. } else {
    12. this.simplePrefix = this.placeholderPrefix;
    13. }
    14. this.valueSeparator = valueSeparator;
    15. this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
    16. }

就 PropertySourcesPropertyResolver 而言,其父类 AbstractPropertyResolver 已经对上述四个值做了定义:

  • placeholderPrefix${
  • placeholderSuffix}
  • valueSeparator:
  • ignoreUnresolvablePlaceholders ,默认为 false ,当然我们也可以使用相应的 setter 方法自定义。

调用 PropertyPlaceholderHelper 的 #replacePlaceholders(String value, PlaceholderResolver placeholderResolver) 方法,对占位符进行处理,该方法接收两个参数,一个是待解析的字符串 value ,一个是 PlaceholderResolver 类型的 placeholderResolver ,他是定义占位符解析的策略类。代码如下:

  1. // PropertyPlaceholderHelper.java
  2. public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) {
  3. Assert.notNull(value, "'value' must not be null");
  4. return parseStringValue(value, placeholderResolver, new HashSet<>());
  5. }
  6. protected String parseStringValue(String value, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) {
  7. StringBuilder result = new StringBuilder(value);
  8. // 获取前缀 "${" 的索引位置
  9. int startIndex = value.indexOf(this.placeholderPrefix);
  10. while (startIndex != -1) {
  11. // 获取 后缀 "}" 的索引位置
  12. int endIndex = findPlaceholderEndIndex(result, startIndex);
  13. if (endIndex != -1) {
  14. // 截取 "${" 和 "}" 中间的内容,这也就是我们在配置文件中对应的值
  15. String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex);
  16. String originalPlaceholder = placeholder;
  17. if (!visitedPlaceholders.add(originalPlaceholder)) {
  18. throw new IllegalArgumentException(
  19. "Circular placeholder reference '" + originalPlaceholder + "' in property definitions");
  20. }
  21. // Recursive invocation, parsing placeholders contained in the placeholder key.
  22. // 解析占位符键中包含的占位符,真正的值
  23. placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);
  24. // Now obtain the value for the fully resolved key...
  25. // 从 Properties 中获取 placeHolder 对应的值 propVal
  26. String propVal = placeholderResolver.resolvePlaceholder(placeholder);
  27. // 如果不存在
  28. if (propVal == null && this.valueSeparator != null) {
  29. // 查询 : 的位置
  30. int separatorIndex = placeholder.indexOf(this.valueSeparator);
  31. // 如果存在 :
  32. if (separatorIndex != -1) {
  33. // 获取 : 前面部分 actualPlaceholder
  34. String actualPlaceholder = placeholder.substring(0, separatorIndex);
  35. // 获取 : 后面部分 defaultValue
  36. String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
  37. // 从 Properties 中获取 actualPlaceholder 对应的值
  38. propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
  39. // 如果不存在 则返回 defaultValue
  40. if (propVal == null) {
  41. propVal = defaultValue;
  42. }
  43. }
  44. }
  45. if (propVal != null) {
  46. // Recursive invocation, parsing placeholders contained in the
  47. // previously resolved placeholder value.
  48. propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
  49. result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
  50. if (logger.isTraceEnabled()) {
  51. logger.trace("Resolved placeholder '" + placeholder + "'");
  52. }
  53. startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length());
  54. } else if (this.ignoreUnresolvablePlaceholders) {
  55. // Proceed with unprocessed value.
  56. // 忽略值
  57. startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
  58. } else {
  59. throw new IllegalArgumentException("Could not resolve placeholder '" +
  60. placeholder + "'" + " in value \"" + value + "\"");
  61. }
  62. visitedPlaceholders.remove(originalPlaceholder);
  63. } else {
  64. startIndex = -1;
  65. }
  66. }
  67. // 返回propVal,就是替换之后的值
  68. return result.toString();
  69. }
  • 其实就是获取占位符 ${} 中间的值,这里面会涉及到一个递归的过程,因为可能会存在这种情况 ${${name}}

2.5 convertValueIfNecessary

#convertValueIfNecessary(Object value, Class<T> targetType) 方法,是不是感觉到非常的熟悉,该方法就是完成类型转换的。代码如下:

  1. // AbstractPropertyResolver.java
  2. @Nullable
  3. protected <T> T convertValueIfNecessary(Object value, @Nullable Class<T> targetType) {
  4. if (targetType == null) {
  5. return (T) value;
  6. }
  7. ConversionService conversionServiceToUse = this.conversionService;
  8. if (conversionServiceToUse == null) {
  9. // Avoid initialization of shared DefaultConversionService if
  10. // no standard type conversion is needed in the first place...
  11. if (ClassUtils.isAssignableValue(targetType, value)) {
  12. return (T) value;
  13. }
  14. conversionServiceToUse = DefaultConversionService.getSharedInstance();
  15. }
  16. // 执行转换
  17. return conversionServiceToUse.convert(value, targetType);
  18. }
  • 首先,获取类型转换服务 conversionService 。若为空,则判断是否可以通过反射来设置,如果可以则直接强转返回,否则构造一个 DefaultConversionService 实例。
  • 最后调用其 #convert(Object source, Class<T> targetType) 方法,完成类型转换。后续就是 Spring 类型转换体系的事情了,如果对其不了解,可以参考小编这篇博客:【死磕 Spring】—— IoC 之深入分析 Bean 的类型转换体系

3. Environment

表示当前应用程序正在运行的环境

应用程序的环境有两个关键方面:profile 和 properties。

  • properties 的方法由 PropertyResolver 定义。
  • profile 则表示当前的运行环境,对于应用程序中的 properties 而言,并不是所有的都会加载到系统中,只有其属性与 profile 一直才会被激活加载,

所以 Environment 对象的作用,是确定哪些配置文件(如果有)当前处于活动状态,以及默认情况下哪些配置文件(如果有)应处于活动状态。properties 在几乎所有应用程序中都发挥着重要作用,并且有多种来源:属性文件,JVM 系统属性,系统环境变量,JNDI,servlet 上下文参数,ad-hoc 属性对象,映射等。同时它继承 PropertyResolver 接口,所以与属性相关的 Environment 对象其主要是为用户提供方便的服务接口,用于配置属性源和从中属性源中解析属性。

代码如下:

  1. // Environment.java
  2. public interface Environment extends PropertyResolver {
  3. // 返回此环境下激活的配置文件集
  4. String[] getActiveProfiles();
  5. // 如果未设置激活配置文件,则返回默认的激活的配置文件集
  6. String[] getDefaultProfiles();
  7. boolean acceptsProfiles(String... profiles);
  8. }

Environment 体系结构图如下:

Environment 类图

  • PropertyResolver:提供属性访问功能
  • Environment:提供访问和判断 profiles 的功能
  • ConfigurableEnvironment:提供设置激活的 profile 和默认的 profile 的功能以及操作 Properties 的工具
  • ConfigurableWebEnvironment:提供配置 Servlet 上下文和 Servlet 参数的功能
  • AbstractEnvironment:实现了 ConfigurableEnvironment 接口,默认属性和存储容器的定义,并且实现了 ConfigurableEnvironment 的方法,并且为子类预留可覆盖了扩展方法
  • StandardEnvironment:继承自 AbstractEnvironment ,非 Servlet(Web) 环境下的标准 Environment 实现
  • StandardServletEnvironment:继承自 StandardEnvironment ,Servlet(Web) 环境下的标准 Environment 实现

3.1 ConfigurableEnvironment

提供设置激活的 profile 和默认的 profile 的功能以及操作 Properties 的工具

该类除了继承 Environment 接口外还继承了 ConfigurablePropertyResolver 接口,所以它即具备了设置 profile 的功能也具备了操作 Properties 的功能。同时还允许客户端通过它设置和验证所需要的属性,自定义转换服务等功能。如下:

  1. // ConfigurableEnvironment.java
  2. public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {
  3. // 指定该环境下的 profile 集
  4. void setActiveProfiles(String... profiles);
  5. // 增加此环境的 profile
  6. void addActiveProfile(String profile);
  7. // 设置默认的 profile
  8. void setDefaultProfiles(String... profiles);
  9. // 返回此环境的 PropertySources
  10. MutablePropertySources getPropertySources();
  11. // 尝试返回 System.getenv() 的值,若失败则返回通过 System.getenv(string) 的来访问各个键的映射
  12. Map<String, Object> getSystemEnvironment();
  13. // 尝试返回 System.getProperties() 的值,若失败则返回通过 System.getProperties(string) 的来访问各个键的映射
  14. Map<String, Object> getSystemProperties();
  15. void merge(ConfigurableEnvironment parent);
  16. }

3.2 AbstractEnvironment

Environment 的基础实现

允许通过设置 ACTIVE_PROFILES_PROPERTY_NAMEDEFAULT_PROFILES_PROPERTY_NAME 属性指定活动和默认配置文件。子类的主要区别在于它们默认添加的 PropertySource 对象。而 AbstractEnvironment 则没有添加任何内容。

  • 子类应该通过受保护的 #customizePropertySources(MutablePropertySources) 钩子提供属性源。方法的代码如下:

    1. // AbstractEnvironment.java
    2. public AbstractEnvironment() {
    3. customizePropertySources(this.propertySources);
    4. }
    5. protected void customizePropertySources(MutablePropertySources propertySources) {
    6. }
  • 而客户端应该使用AbstractEnvironment#getPropertySources() 方法,进行自定义并对 MutablePropertySources API 进行操作。方法的代码如下:

    1. // AbstractEnvironment.java
    2. @Override
    3. public MutablePropertySources getPropertySources() {
    4. return this.propertySources;
    5. }

在 AbstractEnvironment 有两对变量,这两对变量维护着激活和默认配置 profile。如下:

  1. // AbstractEnvironment.java
  2. public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profiles.active";
  3. private final Set<String> activeProfiles = new LinkedHashSet<>();
  4. public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profiles.default";
  5. private final Set<String> defaultProfiles = new LinkedHashSet<>(getReservedDefaultProfiles());
  • 由于实现方法较多,这里只关注两个方法:#setActiveProfiles(String... profiles)#getActiveProfiles()

3.2.1 setActiveProfiles

  1. // AbstractEnvironment.java
  2. @Override
  3. public void setActiveProfiles(String... profiles) {
  4. Assert.notNull(profiles, "Profile array must not be null");
  5. if (logger.isDebugEnabled()) {
  6. logger.debug("Activating profiles " + Arrays.asList(profiles));
  7. }
  8. synchronized (this.activeProfiles) {
  9. // 清空 activeProfiles
  10. this.activeProfiles.clear();
  11. // 遍历 profiles 数组,添加到 activeProfiles 中
  12. for (String profile : profiles) {
  13. // 校验
  14. validateProfile(profile);
  15. this.activeProfiles.add(profile);
  16. }
  17. }
  18. }
  • 该方法其实就是操作 activeProfiles 集合,在每次设置之前都会将该集合清空重新添加,添加之前调用 #validateProfile(String profile) 方法,对添加的 profile 进行校验,如下:

    1. // AbstractEnvironment.java
    2. protected void validateProfile(String profile) {
    3. if (!StringUtils.hasText(profile)) {
    4. throw new IllegalArgumentException("Invalid profile [" + profile + "]: must contain text");
    5. }
    6. if (profile.charAt(0) == '!') {
    7. throw new IllegalArgumentException("Invalid profile [" + profile + "]: must not begin with ! operator");
    8. }
    9. }
    • 这个校验过程比较弱,子类可以提供更加严格的校验规则。

3.2.2 getActiveProfile

getActiveProfiles() 方法,中我们可以猜出这个方法实现的逻辑:获取 activeProfiles 集合即可。代码如下:

  1. // AbstractEnvironment.java
  2. public String[] getActiveProfiles() {
  3. return StringUtils.toStringArray(doGetActiveProfiles());
  4. }
  • 委托给 #doGetActiveProfiles() 方法,代码实现:

    1. // AbstractEnvironment.java
    2. protected Set<String> doGetActiveProfiles() {
    3. synchronized (this.activeProfiles) {
    4. // 如果 activeProfiles 为空,则进行初始化
    5. if (this.activeProfiles.isEmpty()) {
    6. // 获得 ACTIVE_PROFILES_PROPERTY_NAME 对应的 profiles 属性值
    7. String profiles = getProperty(ACTIVE_PROFILES_PROPERTY_NAME);
    8. if (StringUtils.hasText(profiles)) {
    9. // 设置到 activeProfiles 中
    10. setActiveProfiles(StringUtils.commaDelimitedListToStringArray(
    11. StringUtils.trimAllWhitespace(profiles)));
    12. }
    13. }
    14. return this.activeProfiles;
    15. }
    16. }
    • 如果 activeProfiles 为空,则从 Properties 中获取 spring.profiles.active 配置,如果不为空,则调用 #setActiveProfiles(String... profiles) 方法,设置 profile,最后返回。

4. 小结

到这里整个环境&属性已经分析完毕了,至于在后面他是如何与应用上下文结合的,我们后面分析。