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);
		}
	}
}
相关推荐
c***937719 分钟前
Spring Security 官网文档学习
java·学习·spring
k***1951 小时前
SpringBoot 使用 spring.profiles.active 来区分不同环境配置
spring boot·后端·spring
踏浪无痕1 小时前
Maven 依赖冲突的正确处理姿势:别再到处写 exclusion 了
spring boot·spring·maven
过客随尘1 小时前
Spring AOP以及事务详解(二)
spring boot·spring
老神在在0012 小时前
MyBatis02
后端·spring·java-ee·mvc·mybatis
知其然亦知其所以然2 小时前
Java 也能玩高质量 AI 绘图?SpringAI + Azure OpenAI 真香警告!
后端·spring·机器学习
f***6512 小时前
spring 跨域CORS Filter
java·后端·spring
Overt0p2 小时前
抽奖系统 (1)
java·spring boot·spring·java-ee·java-rabbitmq
王桑.2 小时前
WebSocket---一种用于实时传输的网络协议
java·websocket·spring·java-ee
杀死那个蝈坦2 小时前
UV 统计(独立访客统计)
java·jvm·spring·kafka·tomcat·maven