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);
		}
	}
}
相关推荐
Kale又菜又爱玩3 小时前
Sentinel全面解析与实战教程
java·spring·微服务·sentinel·springboot·springcloud
小小鸭程序员5 小时前
在Spring Boot中实现图片上传和修改
java·数据库·python·mysql·spring
kill bert7 小时前
第32周Java微服务入门 Spring开发课程查询功能
java·spring·微服务
爱的叹息8 小时前
关于Spring MVC中@RequestParam注解的详细说明,用于在前后端参数名称不一致时实现参数映射。包含代码示例和总结表格
java·spring·mvc
拉丁解牛说技术9 小时前
一句话让deepseek实现基于Spring AI的AI chatbot
人工智能·spring·程序员
zxhl09279 小时前
Spring MVC 的执行流程以及运行原理
java·spring·mvc
爱的叹息9 小时前
关于Spring MVC中传递数组参数的详细说明,包括如何通过逗号分隔的字符串自动转换为数组,以及具体的代码示例和总结表格
python·spring·mvc
爱的叹息10 小时前
关于Spring MVC中@RequestMapping注解的详细解析,涵盖其核心功能、属性、使用场景及最佳实践
java·spring·mvc
Java小混子11 小时前
Spring MVC
java·spring·mvc
王有品12 小时前
Spring MVC 中 @ResponseBody 注解深度使用教程
spring·mvc