InitializingBean接口只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候会执行该方法
import org.springframework.beans.factory.InitializingBean;
public class TestBean implements InitializingBean{
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("this is afterPropertiesSet");
}
public void test(){
System.out.println("this is a test");
}
}
配置文件中配置:
<bean id="testBean" class="com.TestBean" ></bean>
写一个测试的main方法:
public class Main {
public static void main(String[] args){
ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/java/com/beans.xml");
}
}
后台会输出:this is afterPropertiesSet
如果要执行test()方法要怎么办呢?
<bean id="testBean" class="com.TestBean" init-method="test"></bean>
在配置中加入init-method="test"指定要执行的方法,结果后台会输出:
this is afterPropertiesSet
this is a test
继承InitializingBean接口后实现afterPropertiesSet()方法运行程序afterPropertiesSet()方法是一定先执行的,为什么会先执行呢?
我们看一下AbstractAutowireCapableBeanFactory类中的invokeInitMethods讲解的非常清楚,源码如下:
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable {
//判断是否实现了实现了InitializingBean接口,如果实现了InitializingBean接口,则只掉调用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(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
//直接调用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
return null;
}
},getAccessControlContext());
} catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//直接调用afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
//判断是否指定了init-method方法,如果指定了init-method方法会调用制定的init-method
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//init-method方法中指定的方法是通过反射实现
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}