Spring参数动态绑定的原理

简介: 在Spring体系下,如果实现了ConfigurationProperties则会自动刷新。而如果只使用`@Value`的方法,要加上 `@RefreshScope` 才能实现。本篇文章我们来分别研究下他们的原理。然后在来看看其他的方案是如何做的吧。

一、如何实现动态配置

在Spring体系下,如果实现了ConfigurationProperties则会自动刷新。而如果只使用@Value的方法,要加上 @RefreshScope 才能实现。
本篇文章我们来分别研究下他们的原理。然后在来看看其他的方案是如何做的吧。

二、实现原理

2.1 @ConfigurationProperties

所有被@ConfigurationProperties修饰的类都会被ConfigurationPropertiesBeans处理

  1. 实现BeanPostProcessor处理器,初始化时候判断是否被@ConfigurationProperties修饰,如果是就保存到ConfigurationPropertiesBeans#beans属性中
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        // 1. 如果已经被RefreshScope修饰了,也会自动更新就不用在处理了。     
        if (isRefreshScoped(beanName)) {
            return bean;
        }
        ConfigurationProperties annotation = AnnotationUtils
                .findAnnotation(bean.getClass(), ConfigurationProperties.class);
        if (annotation != null) {
            this.beans.put(beanName, bean);
        }
        else if (this.metaData != null) {
            annotation = this.metaData.findFactoryAnnotation(beanName,
                    ConfigurationProperties.class);
            if (annotation != null) {
                this.beans.put(beanName, bean);
            }
        }
        return bean;
    }
  1. ConfigurationPropertiesRebinder 实现 EnvironmentChangeEvent 变更事件, 当收到EnvironmentChangeEvent事件

会重新触发绑定事件。需要绑定的bean就从ConfigurationPropertiesBeans#beans属性中获取。

具体的实现类 ConfigurationPropertiesRebinder

  1. 先调用销毁方法
  2. 然后重新初始化
    // 接受事件
    public void onApplicationEvent(EnvironmentChangeEvent event) {
        if (this.applicationContext.equals(event.getSource())
                // Backwards compatible
                || event.getKeys().equals(event.getSource())) {
            rebind();
        }
    }
    // 重新绑定
    public boolean rebind(String name) {
        if (!this.beans.getBeanNames().contains(name)) {
            return false;
        }
        if (this.applicationContext != null) {
            try {
                Object bean = this.applicationContext.getBean(name);
                if (AopUtils.isAopProxy(bean)) {
                    bean = ProxyUtils.getTargetObject(bean);
                }
                if (bean != null) {
                    this.applicationContext.getAutowireCapableBeanFactory()
                            .destroyBean(bean);
                    this.applicationContext.getAutowireCapableBeanFactory()
                            .initializeBean(bean, name);
                    return true;
                }
            }
            catch (RuntimeException e) {
                this.errors.put(name, e);
                throw e;
            }
            catch (Exception e) {
                this.errors.put(name, e);
                throw new IllegalStateException("Cannot rebind to " + name, e);
            }
        }
        return false;
    }

2.2 @RefreshScope

@RefreshScope 的原理相对流程较长,首先他需要你将类用 @RefreshScope来修饰。

  1. 首先明确那些是被修饰的AnnotatedBeanDefinitionReader#registerBean。
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
            @Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {

        AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
        if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
            return;
        }

        abd.setInstanceSupplier(instanceSupplier);
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
        abd.setScope(scopeMetadata.getScopeName());
        ...
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
        // 创建bean描述信息 beanClass = ScopedProxyFactoryBean
        // ScopedProxyCreator#createScopedProxy->ScopedProxyUtils#createScopedProxy
        definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
        BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);

}        
  1. 被Scope修饰的beanClass都是ScopedProxyFactoryBean

    • GenericScope 实现BeanFactoryPostProcessor 会提前将RefreshScope注册到BeanFactory中
    • beanFactory.registerScope(this.name, this)
    • 当执行完上面 AbstractBeanFactory#scopes属性中就有值了。对于RefreshScope name = refresh
public class GenericScope implements Scope, BeanFactoryPostProcessor,
        BeanDefinitionRegistryPostProcessor, DisposableBean {

}
public class RefreshScope extends GenericScope implements ApplicationContextAware,
        ApplicationListener<ContextRefreshedEvent>, Ordered {    
}        
  1. 当getBean时候,对于域对象会有特殊的处理逻辑,会调用 Scope#get(String name, ObjectFactory<?> objectFactory)
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
            ...
                // 创建单例逻辑
                if (mbd.isSingleton()) {
                    ...
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }
                // 创建原型逻辑
                else if (mbd.isPrototype()) {
                    ...
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }
                else {
                    // 创建域对象
                    // refresh
                    String scopeName = mbd.getScope();
                    // RefreshScope
                    final Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, () -> {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            finally {
                                afterPrototypeCreation(beanName);
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                }
            }
        }
        return (T) bean;
    }
public interface Scope {
    Object get(String name, ObjectFactory<?> objectFactory); 
}
public class GenericScope implements Scope, BeanFactoryPostProcessor,
        BeanDefinitionRegistryPostProcessor, DisposableBean {}
public class RefreshScope extends GenericScope implements ApplicationContextAware,
        ApplicationListener<ContextRefreshedEvent>, Ordered {}        
  1. RefreshEventListener 接受事件,触发刷新操作
public class RefreshEventListener implements SmartApplicationListener {
    private ContextRefresher refresh;
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            handle((ApplicationReadyEvent) event);
        }
        else if (event instanceof RefreshEvent) {
            handle((RefreshEvent) event);
        }
    }

    public void handle(ApplicationReadyEvent event) {
        this.ready.compareAndSet(false, true);
    }

    public void handle(RefreshEvent event) {
        if (this.ready.get()) { // don't handle events before app is ready
            log.debug("Event received " + event.getEventDesc());
            Set<String> keys = this.refresh.refresh();
            log.info("Refresh keys changed: " + keys);
        }
    }
}
  1. ContextRefresher#refresh

    1. refreshEnvironment刷新环境
    2. 调用RefreshScope#refreshAll
public class ContextRefresher {
   public synchronized Set<String> refresh() {
        Set<String> keys = refreshEnvironment();
        this.scope.refreshAll();
        return keys;
    }

    public synchronized Set<String> refreshEnvironment() {
        Map<String, Object> before = extract(
                this.context.getEnvironment().getPropertySources());
        addConfigFilesToEnvironment();
        Set<String> keys = changes(before,
                extract(this.context.getEnvironment().getPropertySources())).keySet();
        this.context.publishEvent(new EnvironmentChangeEvent(this.context, keys));
        return keys;
    }
}
  1. RefreshScope#refreshAll

会将容器中的bean给销毁。
而ScopedProxyFactoryBean中getObject是一个代理对象。带代理类每次都从容器中获取。而容器前面已经将被RefreshScope修饰的类给销毁了
测试拿到的对象就是重新从容器中生成的。

public class ScopedProxyFactoryBean extends ProxyConfig
        implements FactoryBean<Object>, BeanFactoryAware, AopInfrastructureBean {
    private Object proxy;    
    private final SimpleBeanTargetSource scopedTargetSource = new SimpleBeanTargetSource();
    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        ...
        ProxyFactory pf = new ProxyFactory();
        pf.copyFrom(this);
        pf.setTargetSource(this.scopedTargetSource);
        this.proxy = pf.getProxy(cbf.getBeanClassLoader());
    }
}        

public class SimpleBeanTargetSource extends AbstractBeanFactoryBasedTargetSource {
    @Override
    public Object getTarget() throws Exception {
        return getBeanFactory().getBean(getTargetBeanName());
    }
}

三、其他方案

因为我们项目中用的是阿波罗,那我们只看阿波罗是如何来做的吧。
在阿波罗只用使用@Value就行了

3.1 先扫描@Value注解

将被@Value修饰的Bean和配置key先生成一个SpringValue对象然后注册到SpringValueRegistry中

public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor, BeanFactoryAware {
   protected void processField(Object bean, String beanName, Field field) {
       // register @Value on field
       Value value = field.getAnnotation(Value.class);
       if (value == null) {
         return;
       }
       Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());
   
       if (keys.isEmpty()) {
         return;
       }
   
       for (String key : keys) {
         SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false);
         springValueRegistry.register(beanFactory, key, springValue);
         logger.debug("Monitoring {}", springValue);
       }
  }
}

3.2 找到需要更新的Bean

接受到配置变更事件后,遍历本地变更的配置key,然后将本次key关联需要变更的Bean,从springValueRegistry中找到。

public class AutoUpdateConfigChangeListener implements ConfigChangeListener{
   @Override
  public void onChange(ConfigChangeEvent changeEvent) {
    Set<String> keys = changeEvent.changedKeys();
    if (CollectionUtils.isEmpty(keys)) {
      return;
    }
    for (String key : keys) {
      // 1. check whether the changed key is relevant
      Collection<SpringValue> targetValues = springValueRegistry.get(beanFactory, key);
      if (targetValues == null || targetValues.isEmpty()) {
        continue;
      }

      // 2. update the value
      for (SpringValue val : targetValues) {
        updateSpringValue(val);
      }
    }
  }
}

3.3 通过反射的方法注入

public class SpringValue {
   public void update(Object newVal) throws IllegalAccessException, InvocationTargetException {
       if (isField()) {
         injectField(newVal);
       } else {
         injectMethod(newVal);
       }
     }
    private void injectField(Object newVal) throws IllegalAccessException {
       Object bean = beanRef.get();
       if (bean == null) {
         return;
       }
       boolean accessible = field.isAccessible();
       field.setAccessible(true);
       field.set(bean, newVal);
       field.setAccessible(accessible);
     }
}

非常简单,高效。相比使用@RefreshScope是不是清爽多了呢?

相关文章
|
缓存 Java 开发者
【Spring】原理:Bean的作用域与生命周期
本文将围绕 Spring Bean 的作用域与生命周期展开深度剖析,系统梳理作用域的类型与应用场景、生命周期的关键阶段与扩展点,并结合实际案例揭示其底层实现原理,为开发者提供从理论到实践的完整指导。
1268 22
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
3269 0
|
存储 人工智能 自然语言处理
RAG 调优指南:Spring AI Alibaba 模块化 RAG 原理与使用
通过遵循以上最佳实践,可以构建一个高效、可靠的 RAG 系统,为用户提供准确和专业的回答。这些实践涵盖了从文档处理到系统配置的各个方面,能够帮助开发者构建更好的 RAG 应用。
7609 117
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
1090 2
|
前端开发 Java 数据库连接
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
|
XML Java 开发者
Spring Boot开箱即用可插拔实现过程演练与原理剖析
【11月更文挑战第20天】Spring Boot是一个基于Spring框架的项目,其设计目的是简化Spring应用的初始搭建以及开发过程。Spring Boot通过提供约定优于配置的理念,减少了大量的XML配置和手动设置,使得开发者能够更专注于业务逻辑的实现。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,为开发者提供一个全面的理解。
493 0
|
Java 关系型数据库 数据库
深度剖析【Spring】事务:万字详解,彻底掌握传播机制与事务原理
在Java开发中,Spring框架通过事务管理机制,帮我们轻松实现了这种“承诺”。它不仅封装了底层复杂的事务控制逻辑(比如手动开启、提交、回滚事务),还提供了灵活的配置方式,让开发者能专注于业务逻辑,而不用纠结于事务细节。
1409 1
|
前端开发 Java 数据库连接
Spring核心原理剖析与解说
每个部分都是将一种巨大并且复杂的技术理念传达为更易于使用的接口,而这就是Spring的价值所在,它能让你专注于开发你的应用,而不必从头开始设计每一部分。
475 32
|
缓存 安全 Java
Spring 框架核心原理与实践解析
本文详解 Spring 框架核心知识,包括 IOC(容器管理对象)与 DI(容器注入依赖),以及通过注解(如 @Service、@Autowired)声明 Bean 和注入依赖的方式。阐述了 Bean 的线程安全(默认单例可能有安全问题,需业务避免共享状态或设为 prototype)、作用域(@Scope 注解,常用 singleton、prototype 等)及完整生命周期(实例化、依赖注入、初始化、销毁等步骤)。 解析了循环依赖的解决机制(三级缓存)、AOP 的概念(公共逻辑抽为切面)、底层动态代理(JDK 与 Cglib 的区别)及项目应用(如日志记录)。介绍了事务的实现(基于 AOP
635 0