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);
		}
	}
}
相关推荐
风流 少年15 分钟前
Spring AI 2.0:Hello World
java·人工智能·spring
@卓越俊逸_角立杰出@6 小时前
java实现Agent+ReAct demo(Spring Boot + Spring AI Alibaba ReAct Agent)
java·spring·react.js
不才不才不不才7 小时前
Spring 源码系列(20): @SpringBootApplication 三注解拆解
java·后端·spring
少晓年18 小时前
Spring Security OAuth2.0 自定义过滤器实践:从原理到实战
spring
盗理者1 天前
AI Agent 技能分享|SQL 性能诊断与优化
java·sql·spring·skill
月光有害1 天前
理解 Spring 依赖注入:从构造器注入到集合与条件 Bean
java·后端·spring
小当家.1051 天前
LLM服务缓存与连接池管理:三层缓存架构与ChatClient池化
java·后端·spring·缓存·llm·agent
小当家.1051 天前
Token成本控制实战:语义缓存、上下文压缩与工具缓存
java·spring·缓存·token·上下文
IT利刃出鞘1 天前
SpringBoot--解决@Valid放在接口的List上时无效的问题
java·spring
IKUN家族2 天前
Spring IoC&DI
java·spring·rpc