关于Spring属性处理器PropertyResolver以及应用运行环境Environment的深度分析,强大的StringValueResolver使用和解析【享学Spring】(中)

简介: 关于Spring属性处理器PropertyResolver以及应用运行环境Environment的深度分析,强大的StringValueResolver使用和解析【享学Spring】(中)

ConfigurableEnvironment


扩展出了修改和配置profiles的一系列方法,包括用户自定义的和系统相关的属性。所有的环境实现类也都是它的实现~

// @since 3.1
public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {
  void setActiveProfiles(String... profiles);
  void addActiveProfile(String profile);
  void setDefaultProfiles(String... profiles);
  // 获取到所有的属性源~   MutablePropertySources表示可变的属性源们~~~ 它是一个聚合的  持有List<PropertySource<?>>
  // 这样获取出来后,我们可以add或者remove我们自己自定义的属性源了~
  MutablePropertySources getPropertySources();
  // 这里两个哥们应该非常熟悉了吧~~~
  Map<String, Object> getSystemProperties();
  Map<String, Object> getSystemEnvironment();
  // 合并两个环境配置信息~  此方法唯一实现在AbstractEnvironment上
  void merge(ConfigurableEnvironment parent);
}


它会有两个分支:


  1. ConfigurableWebEnvironment:显然它和web环境有关,提供方法void initPropertySources(@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig)让web自己做资源初始化~
  2. AbstractEnvironment:这个是重点,如下~


AbstractEnvironment


它是对环境的一个抽象实现,很重要。


public abstract class AbstractEnvironment implements ConfigurableEnvironment {
  public static final String IGNORE_GETENV_PROPERTY_NAME = "spring.getenv.ignore";
  public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profiles.active";
  public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profiles.default";
  // 保留的默认的profile值   protected final属性,证明子类可以访问
  protected static final String RESERVED_DEFAULT_PROFILE_NAME = "default";
  private final Set<String> activeProfiles = new LinkedHashSet<>();
  // 显然这个里面的值 就是default这个profile了~~~~
  private final Set<String> defaultProfiles = new LinkedHashSet<>(getReservedDefaultProfiles());
  // 这个很关键,直接new了一个 MutablePropertySources来管理属性源们
  // 并且是用的PropertySourcesPropertyResolver来处理里面可能的占位符~~~~~
  private final MutablePropertySources propertySources = new MutablePropertySources();
  private final ConfigurablePropertyResolver propertyResolver = new PropertySourcesPropertyResolver(this.propertySources);
  // 唯一构造方法  customizePropertySources是空方法,交由子类去实现,对属性源进行定制~ 
  // Spring对属性配置分出这么多曾经,在SpringBoot中有着极其重要的意义~~~~
  public AbstractEnvironment() {
    customizePropertySources(this.propertySources);
  }
  // 该方法,StandardEnvironment实现类是有复写的~
  protected void customizePropertySources(MutablePropertySources propertySources) {
  }
  // 若你想改变默认default这个值,可以复写此方法~~~~
  protected Set<String> getReservedDefaultProfiles() {
    return Collections.singleton(RESERVED_DEFAULT_PROFILE_NAME);
  }
  //  下面开始实现接口的方法们~~~~~~~
  @Override
  public String[] getActiveProfiles() {
    return StringUtils.toStringArray(doGetActiveProfiles());
  }
  protected Set<String> doGetActiveProfiles() {
    synchronized (this.activeProfiles) {
      if (this.activeProfiles.isEmpty()) { 
        // 若目前是empty的,那就去获取:spring.profiles.active
        String profiles = getProperty(ACTIVE_PROFILES_PROPERTY_NAME);
        if (StringUtils.hasText(profiles)) {
          //支持,分隔表示多个~~~且空格啥的都无所谓
          setActiveProfiles(StringUtils.commaDelimitedListToStringArray(
              StringUtils.trimAllWhitespace(profiles)));
        }
      }
      return this.activeProfiles;
    }
  }
  @Override
  public void setActiveProfiles(String... profiles) {
    synchronized (this.activeProfiles) {
      this.activeProfiles.clear(); // 因为是set方法  所以情况已存在的吧
      for (String profile : profiles) {
         // 简单的valid,不为空且不以!打头~~~~~~~~
        validateProfile(profile);
        this.activeProfiles.add(profile);
      }
    }
  }
  // default profiles逻辑类似,也是不能以!打头~
  @Override
  @Deprecated
  public boolean acceptsProfiles(String... profiles) {
    for (String profile : profiles) {
      // 此处:如果该profile以!开头,那就截断出来  把后半段拿出来看看   它是否在active行列里~~~ 
      // 此处稍微注意:若!表示一个相反的逻辑~~~~~请注意比如!dev表示若dev是active的,我反倒是不生效的
      if (StringUtils.hasLength(profile) && profile.charAt(0) == '!') {
        if (!isProfileActive(profile.substring(1))) {
          return true;
        }
      } else if (isProfileActive(profile)) {
        return true;
      }
    }
    return false;
  }
  // 采用函数式接口处理  就非常的优雅了~
  @Override
  public boolean acceptsProfiles(Profiles profiles) {
    Assert.notNull(profiles, "Profiles must not be null");
    return profiles.matches(this::isProfileActive);
  }
  // 简答的说要么active包含,要门是default  这个profile就被认为是激活的
  protected boolean isProfileActive(String profile) {
    validateProfile(profile);
    Set<String> currentActiveProfiles = doGetActiveProfiles();
    return (currentActiveProfiles.contains(profile) ||
        (currentActiveProfiles.isEmpty() && doGetDefaultProfiles().contains(profile)));
  }
  @Override
  public MutablePropertySources getPropertySources() {
    return this.propertySources;
  }
  public Map<String, Object> getSystemProperties() {
    return (Map) System.getProperties();
  }
  public Map<String, Object> getSystemEnvironment() {
    // 这个判断为:return SpringProperties.getFlag(IGNORE_GETENV_PROPERTY_NAME);
    // 所以我们是可以通过在`spring.properties`这个配置文件里spring.getenv.ignore=false关掉不暴露环境变量的~~~
    if (suppressGetenvAccess()) {
      return Collections.emptyMap();
    }
    return (Map) System.getenv();
  }
  // Append the given parent environment's active profiles, default profiles and property sources to this (child) environment's respective collections of each.
  // 把父环境的属性合并进来~~~~  
  // 在调用ApplicationContext.setParent方法时,会把父容器的环境合并进来  以保证父容器的属性对子容器都是可见的
  @Override
  public void merge(ConfigurableEnvironment parent) {
    for (PropertySource<?> ps : parent.getPropertySources()) {
      if (!this.propertySources.contains(ps.getName())) {
        this.propertySources.addLast(ps); // 父容器的属性都放在最末尾~~~~
      }
    }
    // 合并active
    String[] parentActiveProfiles = parent.getActiveProfiles();
    if (!ObjectUtils.isEmpty(parentActiveProfiles)) {
      synchronized (this.activeProfiles) {
        for (String profile : parentActiveProfiles) {
          this.activeProfiles.add(profile);
        }
      }
    }
    // 合并default
    String[] parentDefaultProfiles = parent.getDefaultProfiles();
    if (!ObjectUtils.isEmpty(parentDefaultProfiles)) {
      synchronized (this.defaultProfiles) {
        this.defaultProfiles.remove(RESERVED_DEFAULT_PROFILE_NAME);
        for (String profile : parentDefaultProfiles) {
          this.defaultProfiles.add(profile);
        }
      }
    }
  }
  // 其余方法全部委托给内置的propertyResolver属性,因为它就是个`PropertyResolver`
  ...
}


该抽象类完成了对active、default等相关方法的复写处理。它内部持有一个MutablePropertySources引用来管理属性源。


So,留给子类的活就不多了:只需要把你的属性源注册给我就OK了

StandardEnvironment

这个是Spring应用在非web容器运行的环境。从名称上解释为:标准实现


public class StandardEnvironment extends AbstractEnvironment {
  // 这两个值定义着  就是在@Value注解要使用它们时的key~~~~~
  /** System environment property source name: {@value}. */
  public static final String SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME = "systemEnvironment";
  /** JVM system properties property source name: {@value}. */
  public static final String SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME = "systemProperties";
  // 注册MapPropertySource和SystemEnvironmentPropertySource
  // SystemEnvironmentPropertySource是MapPropertySource的子类~~~~
  @Override
  protected void customizePropertySources(MutablePropertySources propertySources) {
    propertySources.addLast(new MapPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
    propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
  }
}


StandardServletEnvironment


这是在web容器(servlet容器)时候的应用的标准环境。


public class StandardServletEnvironment extends StandardEnvironment implements ConfigurableWebEnvironment {
  public static final String SERVLET_CONTEXT_PROPERTY_SOURCE_NAME = "servletContextInitParams";
  public static final String SERVLET_CONFIG_PROPERTY_SOURCE_NAME = "servletConfigInitParams";
  public static final String JNDI_PROPERTY_SOURCE_NAME = "jndiProperties";
  // 放置三个web相关的配置源~  StubPropertySource是PropertySource的一个public静态内部类~~~
  @Override
  protected void customizePropertySources(MutablePropertySources propertySources) {
    propertySources.addLast(new StubPropertySource(SERVLET_CONFIG_PROPERTY_SOURCE_NAME));
    propertySources.addLast(new StubPropertySource(SERVLET_CONTEXT_PROPERTY_SOURCE_NAME));
    // 可以通过spring.properties配置文件里面的spring.jndi.ignore=true关闭对jndi的暴露   默认是开启的
    if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) {
      propertySources.addLast(new JndiPropertySource(JNDI_PROPERTY_SOURCE_NAME));
    }
    super.customizePropertySources(propertySources);
  }
  // 注册servletContextInitParams和servletConfigInitParams到属性配置源头里
  @Override
  public void initPropertySources(@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {
    WebApplicationContextUtils.initServletPropertySources(getPropertySources(), servletContext, servletConfig);
  }
}


注意:这里addFirst和addLast等关系这顺序,进而都关乎着配置最终的生效的。因此下面对比一下web环境和非web环境下属性源们的配置,各位要有感官上的一个认识~~~


非web环境:

image.png


web环境:

image.png


可见web相关配置的属性源的优先级是高于system相关的。

需要注意的是:若使用@PropertySource导入自定义配置,它会位于最底端(优先级最低

另外附上SpringBoot的属性源们:

访问:http://localhost:8080/env得到如下


image.png

相关文章
|
5月前
|
数据采集 人工智能 Java
1天消化完Spring全家桶文档!DevDocs:一键深度解析开发文档,自动发现子URL并建立图谱
DevDocs是一款基于智能爬虫技术的开源工具,支持1-5层深度网站结构解析,能将技术文档处理时间从数周缩短至几小时,并提供Markdown/JSON格式输出与AI工具无缝集成。
202 1
1天消化完Spring全家桶文档!DevDocs:一键深度解析开发文档,自动发现子URL并建立图谱
|
5月前
|
安全 Java API
深入解析 Spring Security 配置中的 CSRF 启用与 requestMatchers 报错问题
本文深入解析了Spring Security配置中CSRF启用与`requestMatchers`报错的常见问题。针对CSRF,指出默认已启用,无需调用`enable()`,只需移除`disable()`即可恢复。对于`requestMatchers`多路径匹配报错,分析了Spring Security 6.x中方法签名的变化,并提供了三种解决方案:分次调用、自定义匹配器及降级使用`antMatchers()`。最后提醒开发者关注版本兼容性,确保升级平稳过渡。
635 2
|
3月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
146 1
|
2月前
|
缓存 安全 Java
Spring 框架核心原理与实践解析
本文详解 Spring 框架核心知识,包括 IOC(容器管理对象)与 DI(容器注入依赖),以及通过注解(如 @Service、@Autowired)声明 Bean 和注入依赖的方式。阐述了 Bean 的线程安全(默认单例可能有安全问题,需业务避免共享状态或设为 prototype)、作用域(@Scope 注解,常用 singleton、prototype 等)及完整生命周期(实例化、依赖注入、初始化、销毁等步骤)。 解析了循环依赖的解决机制(三级缓存)、AOP 的概念(公共逻辑抽为切面)、底层动态代理(JDK 与 Cglib 的区别)及项目应用(如日志记录)。介绍了事务的实现(基于 AOP
100 0
|
2月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
108 0
|
4月前
|
安全 Java API
Spring Boot 功能模块全解析:构建现代Java应用的技术图谱
Spring Boot不是一个单一的工具,而是一个由众多功能模块组成的生态系统。这些模块可以根据应用需求灵活组合,构建从简单的REST API到复杂的微服务系统,再到现代的AI驱动应用。
|
3月前
|
Java 数据库 开发者
Spring Boot 框架超级详细总结及长尾关键词应用解析
本文深入讲解Spring Boot框架的核心概念、功能特性及实际应用,涵盖自动配置、独立运行、starter依赖等优势。通过Web开发、微服务架构、批处理等适用场景分析,结合在线书店实战案例,演示项目初始化、数据库设计、分层架构实现全流程。同时探讨热部署、多环境配置、缓存机制与事务管理等高级特性,助你高效掌握Spring Boot开发技巧。代码示例详尽,适合从入门到进阶的学习者。
1075 0
|
3月前
|
监控 安全 Java
Java 开发中基于 Spring Boot 3.2 框架集成 MQTT 5.0 协议实现消息推送与订阅功能的技术方案解析
本文介绍基于Spring Boot 3.2集成MQTT 5.0的消息推送与订阅技术方案,涵盖核心技术栈选型(Spring Boot、Eclipse Paho、HiveMQ)、项目搭建与配置、消息发布与订阅服务实现,以及在智能家居控制系统中的应用实例。同时,详细探讨了安全增强(TLS/SSL)、性能优化(异步处理与背压控制)、测试监控及生产环境部署方案,为构建高可用、高性能的消息通信系统提供全面指导。附资源下载链接:[https://pan.quark.cn/s/14fcf913bae6](https://pan.quark.cn/s/14fcf913bae6)。
506 0
|
5月前
|
Java 关系型数据库 MySQL
深入解析 @Transactional——Spring 事务管理的核心
本文深入解析了 Spring Boot 中 `@Transactional` 的工作机制、常见陷阱及最佳实践。作为事务管理的核心注解,`@Transactional` 确保数据库操作的原子性,避免数据不一致问题。文章通过示例讲解了其基本用法、默认回滚规则(仅未捕获的运行时异常触发回滚)、因 `try-catch` 或方法访问修饰符不当导致失效的情况,以及数据库引擎对事务的支持要求。最后总结了使用 `@Transactional` 的五大最佳实践,帮助开发者规避常见问题,提升项目稳定性与可靠性。
745 12
|
5月前
|
安全 Java 数据安全/隐私保护
Spring Security: 深入解析 AuthenticationSuccessHandler
本文深入解析了 Spring Security 中的 `AuthenticationSuccessHandler` 接口,它用于处理用户认证成功后的逻辑。通过实现该接口,开发者可自定义页面跳转、日志记录等功能。文章详细讲解了接口方法参数及使用场景,并提供了一个根据用户角色动态跳转页面的示例。结合 Spring Security 配置,展示了如何注册自定义的成功处理器,帮助开发者灵活应对认证后的多样化需求。
167 2

热门文章

最新文章

推荐镜像

更多
  • DNS