spring简易流程分析
// appconfig类
@ComponentScan("com.zhq")
public class AppConfig {
}
//启动类
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
context.addBeanFactoryPostProcessor(new CarBeanFactory());
context.refresh();
1.注册了几个BeanDefinition;
internalConfigurationAnnotationProcessor: RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
internalAutowiredAnnotationProcessor: RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
internalCommonAnnotationProcessor: RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
internalPersistenceAnnotationProcessor: PersistenceAnnotationBeanPostProcessor
internalEventListenerProcessor: RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
internalEventListenerFactory: RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
2.注册AppConfig,添加到BeanDefinition中
DefaultListableBeanFactory:
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
private volatile List beanDefinitionNames = new ArrayList<>(256);
3.添加BeanPostProcessor
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
4.扫描已经注册所有的BeanDefinition
扫描BeanDefinitionRegistryPostProcessor类型的BeanDefinition
继承这个类的进行排序PriorityOrdered、Ordered、普通
并且执行postProcessBeanDefinitionRegistry方法。
1)首先执行的是ConfigurationClassPostProcessor.class中的方法。
2)把符合(类上有@Configuration注解,或者只要存在@Component、@ComponentScan、@Import、@ImportResource四个中的一个,在或者方法上存在@Bean的)条件的BeanDefinition都会解析成配置类。
3)然后会对这写配置类进行解析,并注册成BeanDefinition。
** 解析:拿到扫描路径之后,执行ClassPathBeanDefinitionScanner中的doScan方法。将所有符合条件的类注册成为Beandefinition **
5.实例化非懒加载的单例Bean
1)遍历所有beanDefinitionNames
2)创建单例Bean
3)遍历所有单例Bean,如果继承SmartInitializingSingleton接口,执行afterSingletonsInstantiated()方法