本文已参与周末学习计划,点击查看详情
学习一个开源框架源码最重要的是关注框架系统启动和初始化方法,很多开源框架都选择了与spring-framework进行集成,一方面避免重复造轮子,另一方面利用了spring-framework框架中的一些核心扩展点. spring-framework常见的扩展点如下
InitializingBean、DisposableBean
InitializingBean 和 DisposableBean 是两个标记接口,为 Spring 执行 Bean 初始化和销毁的某些行为提供有用的方法。
- InitializingBean
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
bean 属性设置完,执行此方法
- init-method : 与 InitializingBean 类似的一种机制是 init-method,在 Spring 初始化 Bean 时,可以配置 Bean 的 init-method 属性。init-method 采用的是反射原理,通过读取配置文件中的 init-method 标签直接构建初始化方法。
- @PostConstruct: 这是与 InitializingBean 类似的另一种初始化机制。不难看出,这个注解作用于构造函数之后
执行顺序 :constructor -> @PostConstruct -> afterPropertiesSet -> init-method
源码追踪 :AbstractAutowireCapableBeanFactory#initializeBean; @PostConstruct
DisposableBean
public interface DisposableBean {
void destroy() throws Exception;
}
bean销毁的时候有beanFactory调用执行此方法
跟init-method一样,spring也提供了基于反射机制的 destory-method 和与 @PostConstruct 注解相对应的 @PreDestroy注解
执行顺序 :@PreDestroy -> DisposableBean-> destroyMethod 源码追踪 :AbstractApplicationContext#destroy
BeanFactoryPostProcessor
@FunctionalInterface
public interface BeanFactoryPostProcessor {
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
可以修改容器中的bean definitions
注意: bean definitions还没初始化,这个时候建议不要提前初始化bean definition
BeanPostProcessor
public interface BeanPostProcessor {
/**
* bean初始化之前
*/
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* bean初始化之后
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
可以在 Bean 的实例化过程中对 Bean 做一些自定义处理
扩展类:CommonAnnotationBeanPostProcessor -> InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization
Aware
public interface Aware {
}
一个标记接口,通过一个回调样式的方法由Spring容器通知特定的框架对象。
实际的方法签名由各个子接口决定,但通常应该只包含一个接受单个参数的返回空值的方法。
ApplicationListener
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E event);
static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
return event -> consumer.accept(event.getPayload());
}
}
事件发布和监听,基于观察者模式的扩展
NamespaceHandler
public interface NamespaceHandler {
void init();
@Nullable
BeanDefinition parse(Element element, ParserContext parserContext);
@Nullable
BeanDefinitionHolder decorate(Node source, BeanDefinitionHolder definition, ParserContext parserContext);
}
命名空间处理器 这个可以参照dubbo的DubboNamespaceHandler
Liftcycle、LifecycleProcessor
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}
public interface LifecycleProcessor extends Lifecycle {
void onRefresh();
void onClose();
}
附上一个spring-framework的ioc启动涉及的 Liftcycle、LifecycleProcessor原理图