二、快速理解Spring的加载流程

一、Spring继承结构

1. Spring容器的继承结构

Spring容器的继承结构

常见的容器的实现类有ClassPathXmlApplicationContext、AnnotationConfigApplicationContext这两个实现类。其中一种是基于XML解析的实现类,一种是基于注解扫描的实现类。

2. Spring工厂的继承结构

Spring工厂的继承结构

Spring中默认的工厂的实现类就是DefaultListableBeanFactory,还有一些别名和单例相关的接口没有在图中绘制。

###3、什么是BeanDefinition?

BeanDefinition属性

在高版本的Spring中,BeanDefinition是上图中的内容,可以看到BeanDefinition中有很多属性,其中每个属性有不同的含义,有一些是标识类信息和bean名称的,有继承关系的属性,是否懒加载的属性,是否可被依赖的属性,创建销毁方法指定的属性等。这些属性在Bean的实例化创建过程中起到至关重要的作用。

二、Spring容器的启动方式

1. 通过加载XML的方式

启动Spring容器的方式,在以往WEB项目中,我们是基于web.xml中配置标签来启动一个Spring容器的。

<!--初始化spring 容器:-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring5/exercise/web01/spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

该启动方式是通过类路径来加载spring.xml配置文件来启动Spring容器。在启动的过程中,Spring会对配置文件中配置的一些标签来加载并保存Bean的定义,最后统一通过这些Bean的定义来实例化并缓存对象。

1.1 手动创建加载XML的Spring容器

    @Test
    public void run01(){
        // 基于加载XML配置文件的方式,启动spring容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:spring5/**/demo01/spring.xml");
        ProductService productService = (ProductService) context.getBean("productService");
        productService.show();
    }

2. 通过扫描注解的方式

当下SpringBoot大行其道,抛开XML配置,基于扫描扫描包/类注解的方式来启动Spring容器才是当下的主流。

2.1 手动创建扫描包路径的Spring容器

    @Test
    public void run02(){
        // 基于扫描注解的方式,启动spring容器
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext("com.jd.nlp.dev.muzi.spring5.exercise.demo01");
        ProductService productService = (ProductService) context.getBean("productService");
        productService.show();
    }

2.2 手动创建扫描类注解的Spring容器

    @Test
    public void run06(){
        // 基于扫描注解的方式,启动spring容器  ScanClass配置了@ComponentScan注解
        AnnotationConfigApplicationContext context =
                new AnnotationConfigAppli
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值