天天看点

spring源码阅读(1)- ioc依赖注入之"helloworld"

public static void main(String[] args){
        ClassPathResource classPathResource = new ClassPathResource("iocarch/beanlifecycle2/springcontext.xml");
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader builder = new XmlBeanDefinitionReader(beanFactory);
        builder.loadBeanDefinitions(classPathResource);

        User user = (User) beanFactory.getBean("user");
    }
           

上面这段程序我们可以看成spring容器的ioc模块的hello world,下面分别从宏观和微观两个面去说明上面的程序。

首先我们应该要了解IOC容器是用来做什么的(不知道的还是先从功能使用上了解IOC容器,不要直接在懵懵懂懂的了解形势下来看源码),先看下图-摘自精通spring4.x

spring源码阅读(1)- ioc依赖注入之"helloworld"

1、IOC容器从xml配置、@Configuration注解的类等读取配置的bean信息,在容器中通过beanDefinition表述,容器维护一个beanDefinition注册列表,

2、容器根据beanDefinition列表实例化对应的Bean对象,将需要管理的实例缓存到容器的池中。

3、应用从容器获取bean,容器从缓存中获取一个或者实例化一个。

这三点极尽简单的说明了IOC依赖注入的原理和功能:类的实例化管理由spring实现,从此应用从类的实例化配置代码中解放,直接从spring中拿来用就ok了。

1、资源

ClassPathResource classPathResource = new ClassPathResource("iocarch/beanlifecycle2/springcontext.xml")
           

这段代码是配置bean实例化方式的xml文件资源的获取,这个点不深入了我们只要知道是到对应的路径获取到文件就行了。

2、工厂

DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
           
DefaultListableBeanFactory:这个是整个bean加载的核心,这个类根据生成了的BeanDefinition列表根据不同的定义对bean进行对应的加载和管理。      

3、读取配置

XmlBeanDefinitionReader builder = new XmlBeanDefinitionReader(beanFactory);
           

该部分主要处理的是xml配置的bean信息,生成BeanDefinition列表。

本章我们通过一小段代码引入IOC实现中的三大功能模块,其中资源部分没有打算深入剖析,接下来我们会顺着读取资源配置->实例化bean管理的路线进行展开深入剖析。

温馨提示:展开的读我这里也会做到点到即止,我们的目标是了解脉络,不是来学习编程和代码设计的。

继续阅读