Spring IOC 容器源码深度剖析

一、IOC:IOC容器的组成逻辑与体系结构
二、beanFactory 对Bean的实例化过程
三、Beandefinition 定义的组成
四、依赖注入的实现逻辑
首先基于xml的加载,然后把它转化成Documnet,然后注册到Bean工厂里,完成我们的注册以后,接着:通过BeanFactory的getBean方法获取BeanDefinition,拿到对应的BeanDefinition之后,它就可以创建bean啦,创建完了以后,调用getBean()方法,返回。

这里写图片描述

package org.nero.click;

import org.junit.Test;
import org.nero.click.data.service.impl.DataServiceImpl;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;

public class BeanFactoryTest {
    //创建bean
    @Test
    public void createBeanTest() {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        DataServiceImpl bean = factory.createBean(DataServiceImpl.class);
        System.out.println(bean);
    }

    //存储bean
    @Test
    public void BeanStoreTest() {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        factory.registerSingleton("service", new DataServiceImpl());
        factory.getBean("Service");
    }


    //依赖关系注入
    @Test
    public void dependcsTest() {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        DataServiceImpl bean = (DataServiceImpl) factory.createBean(DataServiceImpl.class,
                AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
        System.out.println(bean);
    }

    //获取bean
    @Test
    public void getBeanTest() {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
        reader.loadBeanDefinitions("spring.xml");
        DataServiceImpl bean = factory.getBean(DataServiceImpl.class);
    }
}

package org.nero.click;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationTest {
    @Test
    public void contextTest(){

        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");

        context.start();

        context.getBean("DataServiceImp");
        //1、加载资源 xml

        //2、先创建beanFactory、解析xml 文件至beanDefinition 并注册到factory当中去

        //3、对beanFactory进行初始化,对bean(Singleton、非LazyInit、非抽象的bean)进行创建
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_37243717/article/details/80025521