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);
		}
	}
}
相关推荐
无心水1 天前
【任务调度:数据库锁 + 线程池实战】3、 从 SELECT 到 UPDATE:深入理解 SKIP LOCKED 的锁机制与隔离级别
java·分布式·科技·spring·架构
爱跑步的程序员~2 天前
Spring AI会话记忆使用与底层实现
人工智能·spring
渣瓦攻城狮2 天前
互联网大厂Java面试:Spring、微服务与消息队列技术详解
java·redis·spring·微服务·消息队列·面试指南·程序员面试
玹外之音2 天前
Spring AI 工具调用实战:手把手教你让 AI 拥有"超能力"
spring·openai
Anastasiozzzz2 天前
阿亮随手记 SpringBoot应用启动预热、@Lazy、Bean作用域、多环境配置
spring boot·spring·oracle
_BugMan2 天前
Spring核心知识清单
java·后端·spring
014.2 天前
2025最新jenkins保姆级教程!!!
java·运维·spring boot·spring·jenkins
w***71102 天前
常见的 Spring 项目目录结构
java·后端·spring
阿在在2 天前
Spring 系列(三):Spring PostProcessor 顶级扩展接口全解析
java·后端·spring
kyrie学java2 天前
使用SpringBoot框架搭建简易的项目
java·spring boot·spring