Spring IOC 容器源码深度剖析

本文详细探讨了Spring框架中IOC容器的工作原理,包括Bean的实例化过程、BeanDefinition的构成及依赖注入的实现逻辑。通过具体示例展示了如何使用BeanFactory进行Bean的创建、存储与获取,并介绍了依赖关系的注入方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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)进行创建
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值