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

前言

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

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

二、类文件内容

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:c="http://www.springframework.org/schema/c"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xmlns:mvc="http://www.springframework.org/schema/mvc"
 8     xmlns:p="http://www.springframework.org/schema/p"
 9     xmlns:tx="http://www.springframework.org/schema/tx"
10     xmlns:util="http://www.springframework.org/schema/util"
11     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
12         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
13         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
14         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
15         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
16         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
17 
18 <bean id="car" class="com.slp.Car"></bean>
19 </beans>
 1 package com.slp;
 2 /**
 3  * 
 4  * @ClassName:  Car   
 5  * @Description:测试类  
 6  * @author: liping.sang
 7  * @date:   2017年9月22日 上午8:55:37   
 8  *     
 9  * @Copyright: 2017 liping.sang Inc. All rights reserved.
10  */
11 public class Car {
12 
13     private String speed = "200";
14     private String brandName = "BYD";
15     public String getSpeed() {
16         return speed;
17     }
18     public void setSpeed(String speed) {
19         this.speed = speed;
20     }
21     public String getBrandName() {
22         return brandName;
23     }
24     public void setBrandName(String brandName) {
25         this.brandName = brandName;
26     }
27     
28 }
 1 package com.slp;
 2 
 3 import org.springframework.beans.factory.BeanFactory;
 4 import org.springframework.beans.factory.xml.XmlBeanFactory;
 5 import org.springframework.core.io.ClassPathResource;
 6 
 7 public class TestConfig {
 8 
 9     public static void main(String[] args) {
10         // TODO Auto-generated method stub
11         BeanFactory bf  = new XmlBeanFactory(new ClassPathResource("beans.xml"));
12         Car car = (Car) bf.getBean("car");
13         System.out.println(car.getSpeed());//===>200
14     }
15 
16 }

三、功能分析

1、上述完成的功能

1)读取配置文件beans.xml

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

3)调用实例化后的实例

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

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

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

原文地址:https://www.cnblogs.com/dream-to-pku/p/7573985.html