Bean笔记

为什么需要Bean , 因为 Aop 需要。

顺序

InstantiationAwareBeanPostProcessor , BeanPostProcessor 每个Bean都会执行这两个组件的相关方法.

这两个组件的执行顺序

1. InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation
2. InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation
3. InstantiationAwareBeanPostProcessor.postProcessPropertyValues
4. InstantiationAwareBeanPostProcessor.postProcessBeforeInitialization
5. BeanPostProcessor.postProcessBeforeInitialization
6. InstantiationAwareBeanPostProcessor.postProcessAfterInitialization
7. BeanPostProcessor.postProcessAfterInitialization

以下Bean 在3,4之间执行:

    * ApplicationEventPublisherAware
    * MessageSourceAware
    * ApplicationContextAware
    * BeanNameAware
    * BeanClassLoaderAware
    * BeanFactoryAware
    * EnvironmentAware
    * EmbeddedValueResolverAware

即: 执行顺序:
    3. InstantiationAwareBeanPostProcessor.postProcessPropertyValues
    ** (以上bean) **
    4. InstantiationAwareBeanPostProcessor.postProcessBeforeInitialization

InitializingBean 的执行顺序:

5. BeanPostProcessor.postProcessBeforeInitialization
**InitializingBean.@PostConstruct**
**InitializingBean.afterPropertiesSet**
6.InstantiationAwareBeanPostProcessor.postProcessAfterInitialization

自动执行原则

启动类 包名 包含 Bean包的包名. 则 Bean 自动加载.
否则:
1. 需要使用 ComponentScan(包名) 手动加载 .
2. 使用 Import 手动加载单个Bean.

ApplicationListener

Bean生命周期,执行完之后, 会执行 ApplicationListener 相当方法, 依次执行:

ApplicationPreparedEvent : PreInit
AnnotationConfigServletWebServerApplicationContext
ServletWebServerInitializedEvent
ContextRefreshedEvent : Init
ApplicationStartedEvent : Started

底层收集器

如: Json 序列化, 序列化. 底层有方法: ToJson , FromJson .
每个上层可以注册自定义实体序列化方法, 如 ObjectId

底层: 约定, 收集上层定义的Bean:
1. Bean 实现 JsonSerializer 接口. 表示序列化实现.
2. Bean 实现 JsonDeserializer 接口. 表示反序列化实现.

在 BeanPostProcessor.postProcessAfterInitialization 中收集.

posted @ 2018-07-09 16:40  NewSea  阅读(226)  评论(0编辑  收藏  举报