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);
		}
	}
}
相关推荐
m0_748247551 小时前
springboot中配置logback-spring.xml
spring boot·spring·logback
计算机-秋大田2 小时前
基于Spring Boot的农产品智慧物流系统设计与实现(LW+源码+讲解)
java·开发语言·spring boot·后端·spring·课程设计
计算机毕设指导62 小时前
基于SpringBoot的城乡商城协作系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven
caihuayuan43 小时前
PHP建立MySQL持久化连接(长连接)及mysql与mysqli扩展的区别
java·大数据·sql·spring
_风中无我。4 小时前
Spring的过滤器获取请求体中JSON参数,同时解决Controller获取不到请求体参数的问题。
java·spring·json
Swift社区5 小时前
【微服务优化】ELK日志聚合与查询性能提升实战指南
spring·elk·微服务·云原生·架构
White graces15 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
是姜姜啊!17 小时前
redis的应用,缓存,分布式锁
java·redis·spring
奋斗的袍子00718 小时前
Spring AI + Ollama 实现调用DeepSeek-R1模型API
人工智能·spring boot·深度学习·spring·springai·deepseek
LUCIAZZZ18 小时前
EasyExcel快速入门
java·数据库·后端·mysql·spring·spring cloud·easyexcel