一文带你深入理解SpringBean生命周期之InitializingBean详解

简介: 一文带你深入理解SpringBean生命周期之InitializingBean详解

概述


Spring Bean的生命周期是一个比较复杂的过程,从创建到销毁,包含了一些列的过程,本章重点讲解下Spring Bean的afterPropertiesSet()。


InitializingBean介绍


执行阶段


首先我们来回顾下Spring Bean整个生命周期。

1671109620298.jpg

执行阶段: 其中标记黄色部分的就是我们本文的主角,它是在bean的属性被设置值之后,调用bean init-method属性指定的方法之前执行的。


作用


public interface InitializingBean {
  /**
   * Invoked by the containing {@code BeanFactory} after it has set all bean properties
   * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
   * <p>This method allows the bean instance to perform validation of its overall
   * configuration and final initialization when all bean properties have been set.
   * @throws Exception in the event of misconfiguration (such as failure to set an
   * essential property) or if initialization fails for any other reason
   */
  void afterPropertiesSet() throws Exception;
}

InitializingBean只有一个方法afterPropertiesSet,见名知意,这个方法是在bean的属性值被设置以后执行。 Spring给我们提供了这么一个扩展点,可以用来做很多的事情, 比如可以修改默认设置的属性,添加补充额外的属性值或者针对关键属性做一个校验。

Spring本身也有很多的Bean实现了InitializingBean接口, 比如Spring MVC中的RequestMappingHandlerMapping就实现了InitializingBean接口,在afterPropertiesSet中完成了一些初始化工作,比如url和controller方法的映射。


实战案例


  1. 定义bean
@Data
@Slf4j
@ToString
@Accessors(chain = true)
public class BeanLifeCycle implements InitializingBean {
    @Value("${prop:hello}")
    private String prop ;
    public BeanLifeCycle() {
        log.info("#################BeanLifeCycle 实例化");
    }
    public void init() {
        log.info("#################BeanLifeCycle 调用init-mthod 初始化");
    }
    public void destroy() {
        log.info("#################BeanLifeCycle 销毁");
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("#################BeanLifeCycle 调用afterPropertiesSet方法, 查看属性值prop:[{}],已经被赋值", prop);
        log.info("#################BeanLifeCycle 调用afterPropertiesSet 初始化");
    }
}
@Configuration
public class LifeCycleConfig {
    @Bean(name = "beanLifeCycle", initMethod = "init", destroyMethod = "destroy")
    public BeanLifeCycle createBeanLifeCycle() {
        BeanLifeCycle beanLifeCycle = new BeanLifeCycle();
        return beanLifeCycle;
    }
}
  1. 查看执行结果

image.png

执行结果验证了我们的结论,执行afterPropertiesSet()时bean属性已经被初始化,同时它也是在init-method方法前执行。

代码地址:github.com/alvinlkk/sp…


源码解析


上面我们已经了解了InitializingBean的作用和执行时机,现在我们从源码的角度分析下。

image.png

通过debug我们看到,Bean的创建的入口AbstractAutowireCapableBeanFactory的createBean方法,createBean最终调用的是doCreateBean方法。

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
      throws BeanCreationException {
........
 try {     
            // 为bean设置属性值
      populateBean(beanName, mbd, instanceWrapper);
            // 初始化bean
      exposedObject = initializeBean(beanName, exposedObject, mbd);
    }   
........
}

doCreateBean方法中相关的就是populateBean方法和initializeBean方法,populateBean方法主要为bean设置属性值,我们重点关注初始化Bean方法initializeBean。

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
    ........
    try {
            // 执行初始化方法
      invokeInitMethods(beanName, wrappedBean, mbd);
    }
    ......
    return wrappedBean;
  }

initializeBean中关键的是执行invokeInitMethods方法,在这里面调用afterPropertiesSet方法。

protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
      throws Throwable {
        // 判断当前bean是否实现了InitializingBean接口
    boolean isInitializingBean = (bean instanceof InitializingBean);
    // 如果当前bean是一个InitializingBean
        if (isInitializingBean && (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))) {
      if (logger.isTraceEnabled()) {
        logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
      }
      if (System.getSecurityManager() != null) {
        try {
          AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
            ((InitializingBean) bean).afterPropertiesSet();
            return null;
          }, getAccessControlContext());
        }
        catch (PrivilegedActionException pae) {
          throw pae.getException();
        }
      }
      else {
                // 真正调用当前bean的afterPropertiesSet方法
        ((InitializingBean) bean).afterPropertiesSet();
      }
    }
    if (mbd != null && bean.getClass() != NullBean.class) {
      String initMethodName = mbd.getInitMethodName();
      if (StringUtils.hasLength(initMethodName) &&
          !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
          !mbd.hasAnyExternallyManagedInitMethod(initMethodName)) {
        // 最后通过反射的方式执行init-method属性对应的方法
                invokeCustomInitMethod(beanName, bean, mbd);
      }
    }
  }

以上就是从源码层面理解InitializingBean的调用时机。


总结


InitializingBean是Spring中很关键的一个扩展接口,其实它和bean中init-method属性对应的方法功能是一致的,都是初始化bean,我们可以二选一实现即可,当然同时使用也没有问题。init-method是通过反射实现的,性能相对差一点点。另外,如果调用afterPropertiesSet方法时出错,则不会调用init-method指定的方法。

目录
相关文章
|
Java Linux
Springboot 解决linux服务器下获取不到项目Resources下资源
Springboot 解决linux服务器下获取不到项目Resources下资源
|
11月前
|
机器学习/深度学习 算法 小程序
从 GAN 到 Diffusion:移动端图像去水印算法的“算力突围”实战解析
深度解析图像修复(Image Inpainting)技术的演进。探讨如何在微信小程序 2MB 包体积限制下,利用 Serverless 架构实现快速去水印推理。“香蕉一键去水印”的技术架构案例分析。
|
11月前
|
存储 自然语言处理 监控
10 万文档 RAG 落地实战:从 Demo 到生产,我踩过的所有坑
本文分享10万级文档RAG系统从Demo到生产的实战经验,剖析检索慢、召回率低、部署复杂三大痛点,涵盖文档切分、Embedding选型、向量库优化、重排序与生成约束等关键步骤,并提供可落地的工程方案与评估方法,助力构建高效、稳定的企业级RAG系统。
|
8月前
|
人工智能 缓存
阿里云AI通用节省计划是什么意思?Tokens如何计费?包含多少Tokens?
阿里云AI通用节省计划是面向大模型按量付费的折扣机制,用户承诺月消费金额(如200元/年),即可享最高5.3折优惠。它不直接提供固定Tokens,而是按调用模型单价自动抵扣输入/输出Tokens等费用,覆盖全部阿里直供模型,支持灵活生效与自动续费。
|
9月前
|
存储 自然语言处理 并行计算
大模型应用:大模型量化:INT4与INT8核心差异、选型指南及代码实现.53
本文深入解析大模型INT4与INT8量化技术:从“缩放+映射”本质出发,对比二者在压缩率(75% vs 87.5%)、精度(256 vs 16离散值)、显存占用及适用场景的差异;详解scale/zero_point参数原理,并提供BitsAndBytes实战代码,助力高效本地部署。
2027 6
|
NoSQL Java Redis
【小家Spring】Spring Boot中使用RedisTemplate优雅的操作Redis,并且解决RedisTemplate泛型注入失败的问题(中)
【小家Spring】Spring Boot中使用RedisTemplate优雅的操作Redis,并且解决RedisTemplate泛型注入失败的问题(中)
【小家Spring】Spring Boot中使用RedisTemplate优雅的操作Redis,并且解决RedisTemplate泛型注入失败的问题(中)
|
Java Spring
SpringBoot: 启动Banner在线生成工具
SpringBoot: 启动Banner在线生成工具
43419 1
SpringBoot: 启动Banner在线生成工具
|
算法 Java Sentinel
限流算法(计数器、滑动时间窗口、漏斗、令牌)原理以及代码实现
> 本文会对这4个限流算法进行详细说明,并输出实现限流算法的代码示例。 > 代码是按照自己的理解写的,很简单的实现了功能,还请大佬们多多交流找bug。
3429 0
|
Java 编译器 Spring
面试突击78:@Autowired 和 @Resource 有什么区别?
面试突击78:@Autowired 和 @Resource 有什么区别?
18452 7