前言
今天在项目看到一个InitializingBean,不了解是什么作用,特意查了下
InitializingBean
其实,InitializingBean接口是为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。
InitializingBean源码
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
InitializingBean的使用
@Component
public class TestInitialization implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
}
}
以下是AbstractAutowireCapableBeanFactory源码中关于isInitializingBean 的一段代码
/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the merged bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @throws Throwable if thrown by init methods or by the invocation process
* @see #invokeCustomInitMethod
*/
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
//判断该bean是否实现了实现了InitializingBean接口,
//如果实现了InitializingBean接口,则只掉调用bean的afterPropertiesSet方法
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
//调用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//调用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
判断是否指定了init-method方法,如果指定了init-method方法,则再调用制定的init-method
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//查看该方法的源码,可以发现init-method方法中指定的方法是通过反射实现
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
总结
InitializingBean就是为一个类提供了一个初始化方法afterPropertiesSet(),该方法会在初始化bean时执行。还有一种方式,我们也可以使用init-method来指定初始化方法
init-method使用
使用@Bean的initMethod属性就可以指定初始化方法了
@Configuration
public class CustomLifeCycleConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Test2 test2(){
return new Test2 ();
}
}