【Spring源码分析系列】搭建Spring实现容器的基本实现

时间:2023-03-09 16:26:48
【Spring源码分析系列】搭建Spring实现容器的基本实现

前言

bean是Spring中最核心的东西,因为Spring就像一个大水桶,而bean就像是容器中的水,先新建一个小例子来看一下;

一、使用eclipse构建项目,项目结构如下

【Spring源码分析系列】搭建Spring实现容器的基本实现

二、类文件内容

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd"> <bean id="car" class="com.slp.Car"></bean>
</beans>
 package com.slp;
/**
*
* @ClassName: Car
* @Description:测试类
* @author: liping.sang
* @date: 2017年9月22日 上午8:55:37
*
* @Copyright: 2017 liping.sang Inc. All rights reserved.
*/
public class Car { private String speed = "200";
private String brandName = "BYD";
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
} }
 package com.slp;

 import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource; public class TestConfig { public static void main(String[] args) {
// TODO Auto-generated method stub
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml"));
Car car = (Car) bf.getBean("car");
System.out.println(car.getSpeed());//===>200
} }

三、功能分析

1、上述完成的功能

1)读取配置文件beans.xml

2)根据beans.xml中的配置找到对应的类的配置,并实例化

3)调用实例化后的实例

【Spring源码分析系列】搭建Spring实现容器的基本实现

ConfigReader:用于读取及验证配置文件,我们要用配置文件里的内容,首先要读取,然后放入到内存中。

ReflectionUtil:用于根据配置文件中的配置进行反射实例化。

App:用于完成整个逻辑的串联。