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

系列二十二、如何在Spring中所有的bean都创建完成后做扩展

一、哪个地方标识着容器中的bean都创建完成了

循环完所有的DeanDefinition后,bean就创建完了。

# 第一步:
new AnnotationConfigApplicationContext(MySpringConfig.class)

# 第二步:
refresh();

# 第三步:循环所有的BeanDefinition,通过BeanFactory.getBean()生成所有的bean
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
# 1
public AnnotationConfigApplicationContext(String... basePackages) {
		this();
	scan(basePackages);
	refresh();
}
 
# 2、AbstractApplicationContext 550行
finishBeanFactoryInitialization(beanFactory);
 
# 3、AbstractApplicationContext 878行
beanFactory.preInstantiateSingletons();
 
# 4、DefaultListableBeanFactory #preInstantiateSingletons 849~903行
@Override
public void preInstantiateSingletons() throws BeansException {
	if (logger.isTraceEnabled()) {
		logger.trace("Pre-instantiating singletons in " + this);
	}
 
	// Iterate over a copy to allow for init methods which in turn register new bean definitions.
	// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
	List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
 
	// Trigger initialization of all non-lazy singleton beans...
	for (String beanName : beanNames) {
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			if (isFactoryBean(beanName)) {
				Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
				if (bean instanceof FactoryBean) {
					final FactoryBean<?> factory = (FactoryBean<?>) bean;
					boolean isEagerInit;
					if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
						isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
										((SmartFactoryBean<?>) factory)::isEagerInit,
								getAccessControlContext());
					}
					else {
						isEagerInit = (factory instanceof SmartFactoryBean &&
								((SmartFactoryBean<?>) factory).isEagerInit());
					}
					if (isEagerInit) {
						getBean(beanName);
					}
				}
			}
			else {
				getBean(beanName);
			}
		}
	}
 
	// Trigger post-initialization callback for all applicable beans...
	for (String beanName : beanNames) {
		Object singletonInstance = getSingleton(beanName);
		if (singletonInstance instanceof SmartInitializingSingleton) {
			final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
			if (System.getSecurityManager() != null) {
				AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
					smartSingleton.afterSingletonsInstantiated();
					return null;
				}, getAccessControlContext());
			}
			else {
				smartSingleton.afterSingletonsInstantiated();
			}
		}
	}
}
 

二、两种方式

2.1、创建监听器

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/10/25 10:58
 * @Description:
 */
@Component
public class MyContextRefreshedEventExtend {

    @EventListener(ContextRefreshedEvent.class)
    public void onContextRefreshedEvent(ContextRefreshedEvent event) {
        System.out.println(event);
        System.out.println("all singleton beans loaded,onContextRefreshedEvent execute success!");
    }

}

2.2、实现接口

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/10/25 11:03
 * @Description:
 */
@Component
public class MySmartInitializingSingletonExtend implements SmartInitializingSingleton {

    @Override
    public void afterSingletonsInstantiated() {
        System.out.println("all singleton beans loaded,afterSingletonsInstantiated execute success!");
    }
}


http://www.kler.cn/a/107185.html

相关文章:

  • python 同时控制多部手机
  • 前端:块级元素和行内元素
  • ML 系列: 第 23 节 — 离散概率分布 (多项式分布)
  • 常用的Anaconda Prompt命令行指令
  • rockylinux 8安装 gcc11.2
  • 【小程序】封装网络请求request模块
  • MySQL篇---第四篇
  • 论文阅读——InstructGPT
  • 数据库MySQL(四):表中字段约束和外键约束
  • 磁场设备主要有哪些
  • DBA笔记(1)
  • 云服务器搭建Zookeeper集群
  • nginx 动静分离 防盗链
  • 先讲结论、逻辑先行,6个必备的职场技能
  • Ubuntu安装AdGuardhome(树莓派安装AdGuardhome)
  • Centos7 部署 Stable Diffusion
  • JS实现商品SKU
  • Unity地面交互效果——1、局部UV采样和混合轨迹
  • (免费领源码) Asp.Net#SQL Server校园在线投票系统10557-计算机毕业设计项目选题推荐
  • Windows11搭建kafka-python环境
  • 【C程序设计】用心浇灌<C程序>
  • 软考高级之系统架构师之软件工程
  • c++ qt连接操作sqlite
  • 综合性练习
  • 【开源】基于SpringBoot的城市桥梁道路管理系统的设计和实现
  • Java练习题2020-3