前文简单写了下Spring以注解方式加载容器的示例。在此接上文,通过查看AnnotationConfigApplicationContext的源码,来了解Spring的内部机制。Spring容器初始化做了很多操作,此篇文章关注的重点是注册(registry),也就是Spring如何加载的@Configuration注解,以代替了spring xml的配置。至于容器启动时的其他操作留待后续文章中进行讲解。一、切入点配置类注入到 AnnotationConfigApplicationContext 构造函数中,如下代码: //以注解的方式执行 ApplicationContext context = new AnnotationConfigApplicationContext(MySpringConfig.class); 通过这一行代码,就获得了Spring的上下文context,然后context就直接可以通过getBean获得实例对象。很明显AnnotationConfigApplicationContext构造函数做了很多事情,比如:对Spring容器进行了加载。二、相关类图了解首先在此把相关的类做成了一个类图,核心的类和方法如下图所示,下文步骤结合这个类图来看会更加直观。三、源码分析3.1、进入构造函数直接上代码,来看new AnnotationConfigApplicationContext(MySpringConfig.class)里都做了啥: /** * Create a new AnnotationConfigApplicationContext, deriving bean definitions * from the given component classes and automatically refreshing the context. * @param componentClasses one or more component classes — for example, * {@link Configuration @Configuration} classes */ public AnnotationConfigApplicationContext(Class<?>... componentClasses) { this();//初始化类 register(componentClasses);//对配置类进行注册 refresh();//手动刷新 }通过上面代码可以看出,构造函数中干了3件事:1、调用无参构造函数去实例化对象。2、对配置类(示例代码就是:MySpringConfig类)进行注册。3、刷新(Bean工厂、初始化单例对象等)这里主要讲讲1、2步怎么实现的注册进行,刷新方法可以在后续开一篇SpringBean的生命周期,进行讲解。3.2、无参构造函数去实例化对象来看this()里都做了啥:1、为2个类实例化:
全部评论