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);
		}
	}
}
相关推荐
技术宅星云12 小时前
0x00.Spring AI Agent开发指南专栏简介
java·人工智能·spring
蓝眸少年CY12 小时前
(第八篇)spring cloud之zuul路由网关
后端·spring·spring cloud
long31612 小时前
弗洛伊德·沃肖算法 Floyd Warshall Algorithm
java·后端·算法·spring·springboot·图论
IT 行者14 小时前
深入理解 OAuth2/OIDC 中的 Issuer:身份认证的基石
spring
那我掉的头发算什么14 小时前
【SpringBoot】从创建第一个spring项目开始
spring boot·后端·spring
Chan1614 小时前
【 Java八股文面试 | RabbitMQ篇 】
java·spring boot·spring·面试·java-ee·rabbitmq·java-rabbitmq
好大哥呀15 小时前
Java 中的 Spring 框架
java·开发语言·spring
大道之简15 小时前
SpringBoot自定义链路追踪
java·spring boot·spring
hhzz15 小时前
Springboot项目中使用EasyPOI操作Excel(详细教程系列4/4)
java·spring boot·后端·spring·excel·poi·easypoi
爱笑的rabbit16 小时前
Linux和Windows的word模板导出转PDF下载保姆级教程,含PDF图片处理
java·spring