Spring中的InitializingBean接口

使用方法

java 复制代码
@Slf4j
@Component
public class MyBean implements InitializingBean {
 
    public MyBean() {
        log.info("===================> 构造方法");
    }
 
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("===================> afterPropertiesSet方法");
    }
}

Spring中的Bean注入流程


afterPropertieSet()和init-method

在Spring初始化bean的时候,如果该bean实现了InitializingBean接口,并且同时在配置了init-method,系统则是先调用afterPropertieSet()方法,然后再调用init-method中指定的方法。

通过查看Spring加载bean的源码类AbstractAutowiredCapableBeanFactory可以看出:

java 复制代码
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
			throws Throwable {
	// 判断bean是否实现InitializingBean接口
	boolean isInitializingBean = (bean instanceof InitializingBean);
	if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("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 {
			// 执行InitializingBean接口实现的方法
			((InitializingBean) bean).afterPropertiesSet();
		}
	}
 
	if (mbd != null && bean.getClass() != NullBean.class) {
		String initMethodName = mbd.getInitMethodName();
		if (StringUtils.hasLength(initMethodName) &&
				!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
				!mbd.isExternallyManagedInitMethod(initMethodName)) {
			// 使用反射的方式来调用init-method指定的方法
			invokeCustomInitMethod(beanName, bean, mbd);
		}
	}
}
相关推荐
※DX3906※2 分钟前
SpringBoot之旅4: MyBatis 操作数据库(进阶) 动态SQL+MyBatis-Plus实战,从入门到熟练,再也不踩绑定异常、SQL拼接坑
java·数据库·spring boot·spring·java-ee·maven·mybatis
leikooo39 分钟前
我用 SubAgent 做了一个 AI 自动修复闭环:流式修代码、自动构建、失败重试
后端·spring·ai编程
想进大厂的小徐43 分钟前
Spring 容器启动与 Bean 创建流程
java·spring boot·spring
无名-CODING1 小时前
SpringCloud 服务调用与负载均衡:OpenFeign 极简使用教程
spring·spring cloud·负载均衡
Meepo_haha2 小时前
Maven Spring框架依赖包
java·spring·maven
Flittly2 小时前
【SpringAIAlibaba新手村系列】(5)Prompt 提示词基础与多种消息类型
java·笔记·spring·ai·springboot
杜子不疼.2 小时前
高并发场景下 Spring MVC + 虚拟线程 vs WebFlux 选型对比
java·人工智能·spring·mvc
yyt36304584118 小时前
spring单例bean线程安全问题讨论
java·spring
云烟成雨TD20 小时前
Spring AI 1.x 系列【14】三月双版本连发!Spring AI 最新功能全掌握
java·人工智能·spring