1.注入bean工厂
public interface BeanFactoryAware extends Aware {
void setBeanFactory(BeanFactory var1) throws BeansException;
}
2. 应用上下文
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
//此处可以获取特定注解的类
Map<String, Object> beanMap = ctx.getBeansWithAnnotation(Annotation.class)
}
3.bean的初始化和销毁相关
//容器启动后执行,可用于初始化任务
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
//容器销毁前执行
public interface DisposableBean {
void destroy() throws Exception;
}
//bean的后置处理器,所谓后置处理器是指执行完构造器需要执行的方法
public interface BeanPostProcessor {
//自定义初始化方法执行前
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
//自定义初始化方法执行后
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
//初始化方法的执行顺序总结,步骤1-4
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean {
//调用构造器实例化bean之后执行下列逻辑
//依赖注入实现,@Autowired
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
initializeBean{
//实现Aware接口相关
invokeAwareMethods {
BeanNameAware
BeanClassLoaderAware
BeanFactoryAware
}
//1.BeanPostProcessor.postProcessBeforeInitialization
applyBeanPostProcessorsBeforeInitialization
invokeInitMethods {
//2.InitializingBean.afterPropertiesSet
afterPropertiesSet
//3.自定义初始化方法@Bean(initMethod = "init", destroyMethod = "destroy")
invokeCustomInitMethod
}
//4.BeanPostProcessor.postProcessAfterInitialization
applyBeanPostProcessorsAfterInitialization
}
}
//注册DisposableBean
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
4.Aware接口
//实现了SmartLifecycle接口的类会在初始化完成后根据isAutoStartup的返回值确定是否调用start方法
SmartLifecycle
ServletContextAware
Ordered