Spring源码解析之IOC (1)

测试代码链接:spring-learn

spring的IOC模块主要功能就是管理对象的容器

主要分成两个部分: 1.解析用户的配置信息; 2.创建对象并初始化对象

1.解析用户的配置信息

XML配置 :

<bean id="loginServiceImpl" class="com.china.only.user.service.impl.LoginServiceImpl"></bean>

测试代码 :

    public static void testMyBean(){
        AbstractApplicationContext aContext = new ClassPathXmlApplicationContext("beans-ioc.xml");
        LoginServiceImpl loginService = (LoginServiceImpl) aContext.getBean("loginServiceImpl");
        try {
            loginService.login(new HashMap<>());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

ClassPathXmlApplicationContext  从类路径中查找*.xml文件(一般为App ClassLoade类加载的加载路径),这个类返回了代表xml文件资源的数据结构: ClassPathContextResource

ClassPathContextResource,这个类其实封装了一个String类型的资源路径名称和类加载器,然后通过调用该类的getInputStream

	public InputStream getInputStream() throws IOException {
		InputStream is;
		if (this.clazz != null) {
			is = this.clazz.getResourceAsStream(this.path);
		}
		else if (this.classLoader != null) {
			is = this.classLoader.getResourceAsStream(this.path);
		}
		else {
			is = ClassLoader.getSystemResourceAsStream(this.path);
		}
		if (is == null) {
			throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
		}
		return is;
	}

有了xml的InputStream输入流,就可以使用DOM对xml文件进行解析,不熟悉DOM如何解析xml可以自行百度,这个就是Spring框架底层处理xml的方式,由于读取xml实现较为繁琐,我这里使用yaml格式文件代替xml作为框架的配置文件,当然后序可以扩展添加对xml配置文件的支持.

模仿spring的项目: abc

在com.abc.example.Main下的测试代码,读取yaml配置文件:

    public static void testYamlAppContext(){
        ClassPathYamlAppContext context = new ClassPathYamlAppContext("abc.yaml");
        Orange orange = (Orange) context.getBean("orange");
        System.out.println(orange.getName());
        ChineseLesson chineseLesson = (ChineseLesson) context.getBean("lesson");
        chineseLesson.function();
    }

在abc项目中只考虑了类路径下的资源文件加载,所以较spring简化了很多,只要简单封装资源路径即可

    public void registryBeanDefinition() {
        for(String path: pathes){
            Resource resource = new ClassPathResource(path);
            ParserData data = parserFrom(resource);
            registryBeanDefinition(convertToBeanDefinition(data),factory);
        }
    }

 

下一篇文章讲解spring具体如何将xml中用户自定义的bean解析为BeanDefinition这样的数据结构.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值