InitializingBean 为接口,使用后会与spring框架耦合起来,只有一个方法afterPropertiesSet()
init-method 可以在bean的配置文件属性中设置,无耦合
afterPropertiesSet 与init-method 方法相比,afterPropertiesSet()先执行
org.springframework.beans.factory.support. AbstractAutowireCapableBeanFactory完成一个Bean初始化方法的调用工作。 AbstractAutowireCapableBeanFactory是XmlBeanFactory的超类,再 AbstractAutowireCapableBeanFactory的invokeInitMethods方法中实现调用一个Bean初始化方法:
public void invokeInitMethods(String beanName, Object bean, RootBeanDefinition mergedBeanDefinition){
if(bean instanceof InitializingBean){
bean.afterPropertiesSet();
}
if(mergedBeanDefinition != null && mergedBeanDefinition.getInitMethodName() != null){
invokeCustomInitMethod(beanName,bean,mergedBeanDefinition.getInitMethodName() );
}
public void invokeCustomInitMethod(beanName,bean,initMethodName() {
Method initMethod = BeanUtils.findMethod(bean.class,initMethodName);
if(initMethod == null){
throw Exception("no such method");
}
if (!Modifier.isPublic(initMethod.getModifiers())) {
//设置accessible为true,可以访问private方法。
initMethod.setAccessible(true);
}
try{
initMethod.invoke(bean,(Object[])null);
}catch(Exception e){
e.printStackTrace();
}
}