文章目录
Spring启动过程
运行下面代码启动Spring的时候,会经过下面的一些步骤:
创建一个BeanFactory --> 解析指定的配置类 —> 进行包扫描 —> 生成BeanDefinition --> BeanDefinitionMap、BeanpostProcessor、单例池
public static void main(String[] args) {
// 创建一个Spring容器
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = (UserService) context.getBean("userService");
userService.test();
}
创建一个DefaultListableBeanFactory,在创建AnnotationConfigApplicationContext这个类时,会先初始化它的父类,在父类的构造函数中会创建一个DefaultListableBeanFactory
对象,并赋值给BeanFactory属性
// GenericApplicationContext就是AnnotationConfigApplicationContext的父类
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
private final DefaultListableBeanFactory beanFactory;
......
/**
* beanDefinitionMap、beanDefinitionNames等等常见的集合都是在DefaultListableBeanFactory这个类中的
* Create a new GenericApplicationContext.
*/
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
......
}
this()方法
这里主要就是给BeanFactory设置一些内容
接下来回到创建AnnotationConfigApplicationContext类的构造方法中
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
// 构造DefaultListableBeanFactory、AnnotatedBeanDefinitionReader、ClassPathBeanDefinitionScanner
this();
// 通过上一步创建的reader,把将参数传递过来的componentClasses生成BeanDefinition,并存入BeanDefinitionMap中
register(componentClasses);
refresh();
}
// 上面this()方法会到这里来
public AnnotationConfigApplicationContext() {
StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
// 重点就是会创建AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
在创建AnnotatedBeanDefinitionReader
类的构造方法中,最终会调用到AnnotationConfigUtils.registerAnnotationConfigProcessors()
方法中,在该方法中就会往BeanFactory中注册很多常见的BeanPostProcessor。比如判断一个类能不能进行依赖注入、专门解析配置类的、@Autowired和@Resource注解相关的、事件相关的
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
// 设置beanFactory的OrderComparator为AnnotationAwareOrderComparator
// 它是一个Comparator,是一个比较器,可以用来进行排序,比如new ArrayList<>().sort(Comparator);
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
// 用来判断某个Bean能不能用来进行依赖注入
if (