当前位置: 首页 > news >正文

Spring bean的生命周期和扩展

bean生命周期流程

生命周期扩展处理说明
实例化:createBeanInstance

构造方法, 如@Autowired的构造方法注入依赖bean

如UserService构造方法注入AppDAO:

@Autowired
public UserService(AppDAO appDAO) {System.out.println("@Autowired appDAO:" + appDAO);this.appDAO = appDAO;
}
属性设置:populateBean

如setter方法注入的依赖

如@Autoware的filed注入

如UserService中注入UserDAO:

@Resource(name = "u")
public void setUserDAO(UserDAO userDAO) {System.out.println("setUserDAO:" + userDAO);this.userDAO = userDAO;
}
初始化:initializeBean

1. BeanPostProcessor#postProcessBeforeInitialization

2. @PostConstruct

3. InitializingBean#afterPropertiesSet

initMethod

4. BeanPostProcessor#postProcessAfterInitialization

上一步骤属性设置完后,初始化方法前后都可以扩展。

例如BeanPostProcessor#postProcessBeforeInitialization,直接改变了set注入的appDAO对象

@Component
public class ServiceBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {// Bean 初始化前的逻辑if (beanName.equals("userService")) {UserService userService = (UserService)bean;AppDAO appDAO = new AppDAOImpl2();userService.setAppDAO(appDAO);System.out.println("postProcessBeforeInitialization:" + ":" + bean);}return bean;}
销毁

1. @PreDestroy

2. DisposableBean#destroy

destroyMethod

附org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

/*** Actually create the specified bean. Pre-creation processing has already happened* at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.* <p>Differentiates between default bean instantiation, use of a* factory method, and autowiring a constructor.* @param beanName the name of the bean* @param mbd the merged bean definition for the bean* @param args explicit arguments to use for constructor or factory method invocation* @return a new instance of the bean* @throws BeanCreationException if the bean could not be created* @see #instantiateBean* @see #instantiateUsingFactoryMethod* @see #autowireConstructor*/protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {// Instantiate the bean.BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);}final Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if (beanType != NullBean.class) {mbd.resolvedTargetType = beanType;}// Allow post-processors to modify the merged bean definition.synchronized (mbd.postProcessingLock) {if (!mbd.postProcessed) {try {applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed = true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&isSingletonCurrentlyInCreation(beanName));if (earlySingletonExposure) {if (logger.isTraceEnabled()) {logger.trace("Eagerly caching bean '" + beanName +"' to allow for resolving potential circular references");}addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));}// Initialize the bean instance.Object exposedObject = bean;try {populateBean(beanName, mbd, instanceWrapper);exposedObject = initializeBean(beanName, exposedObject, mbd);}catch (Throwable ex) {if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {throw (BeanCreationException) ex;}else {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);}}if (earlySingletonExposure) {Object earlySingletonReference = getSingleton(beanName, false);if (earlySingletonReference != null) {if (exposedObject == bean) {exposedObject = earlySingletonReference;}else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {String[] dependentBeans = getDependentBeans(beanName);Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);for (String dependentBean : dependentBeans) {if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {actualDependentBeans.add(dependentBean);}}if (!actualDependentBeans.isEmpty()) {throw new BeanCurrentlyInCreationException(beanName,"Bean with name '" + beanName + "' has been injected into other beans [" +StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +"] in its raw version as part of a circular reference, but has eventually been " +"wrapped. This means that said other beans do not use the final version of the " +"bean. This is often the result of over-eager type matching - consider using " +"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");}}}}// Register bean as disposable.try {registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch (BeanDefinitionValidationException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);}return exposedObject;}

扩展执行

接上文:AnnotationConfigApplicationContext流程看实例化的beanPostProcessor-CSDN博客,来看这些BeanPostProcessor如何起作用


http://www.mrgr.cn/news/83333.html

相关文章:

  • Java 开发小技巧:使用 String.intern() 优化内存
  • 【JavaEE】—— SpringBoot项目集成百度千帆AI大模型(对话Chat V2)
  • 【HeadFirst系列之HeadFirst设计模式】第1天之HeadFirst设计模式开胃菜
  • ue5 蒙太奇,即上半身动画和下半身组合在一起,并使用。学习b站库得科技
  • 宇航用VIRTEX5系列FPGA的动态刷新方法及实现
  • 【Git原理和使用】Git 分支管理(创建、切换、合并、删除、bug分支)
  • 鸿蒙面试 2025-01-10
  • C#Halcon二维码识别
  • 第十四章 SQL性能分析
  • 【Python】Python之Selenium基础教程+实战demo:提升你的测试+测试数据构造的效率!
  • PySpark广播表连接解决数据倾斜的完整案例
  • 高等数学学习笔记 ☞ 洛必达法则与泰勒公式
  • 【Rust自学】11.5. 在测试中使用Result<T, E>
  • Formality:默认配置文件
  • 【python翻译软件V1.0】
  • 【数据链电台】洛克希德·马丁(Lockheed Martin)
  • P2249 【深基13.例1】查找
  • kubernetes第七天
  • notebook主目录及pip镜像源修改
  • 代码随想录 哈希 test 8
  • 【神经网络中的激活函数如何选择?】
  • 使用 Maxwell 计算母线的电动势
  • 赛车微型配件订销管理系统(源码+lw+部署文档+讲解),源码可白嫖!
  • Formality:工具生成的文件
  • 初学stm32 --- DAC输出
  • 51c~Pytorch~合集4