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 天前
Spring AOP、日志切面与声明式事务原理
java·后端·spring
椰猫子1 天前
SpringBoot(简介、基础配置、整合第三方技术)
java·spring boot·spring
Ting-yu1 天前
Spring AI Alibaba零基础速成(3) ---- ChatClient使用
java·spring·spring cloud·spring ai
IronMurphy2 天前
Redis拷打第六讲
redis·spring·mybatis
Ting-yu2 天前
Spring AI Alibaba零基础速成(2) ---- Ollama安装与使用
java·后端·spring·ai
会编程的吕洞宾2 天前
Spring_Boot_3_3_的___Transactional__
java·后端·spring
那个失眠的夜2 天前
SpringBoot
java·开发语言·spring boot·spring·mvc·mybatis
多敲代码防脱发2 天前
Spring进阶(Bean的生命周期与Bean的后处理器)
java·服务器·开发语言·spring boot·spring·servlet
RingWu2 天前
高并发三板斧-缓存:命中率、一致性、治理
java·spring·缓存
huipeng9262 天前
基于SpringCloud的博客系统
java·运维·后端·spring·spring cloud·微服务