服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring实现一个简单的SpringIOC容器

Spring实现一个简单的SpringIOC容器

2020-09-11 10:23醉眼识朦胧 Java教程

本篇文章主要介绍了Spring实现一个简单的SpringIOC容器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

接触spring快半年了,前段时间刚用spring4+s2h4做完了自己的毕设,但是很明显感觉对spring尤其是ioc容器的实现原理理解的不到位,说白了,就是仅仅停留在会用的阶段,有一颗想读源码的心于是买了一本计文柯的《spring技术内幕》,第二章没看完,就被我扔一边了,看的那是相当痛苦,深深觉得自己资质尚浅,能力还不够,昨天在网上碰巧看到一个实现简单的springioc容器的视频教程,于是跟着做了一遍,竟然相当顺利,至少每一行代码都能理解,于是细心整理了一番,放在这里.

主要思想:

提到ioc,第一反应就是控制反转,我以前以为springioc就是控制反转,控制反转就是springioc,当然这种理解是错误的,控制反转是一种思想,一种模式,而spring的ioc容器是实现了这种思想这种模式的一个载体.

使用过spring的人都熟知,springioc容器可以在对象生成或初始化时就直接将数据注入到对象中,如果对象a的属性是另一个对象b,还可以将这个对象b的引用注入到注入到a的数据域中.

如果在初始化对象a的时候,对象b还没有进行初始化,而a又需要对象b作为自己的属性,那么就会用一种递归的方式进行注入,这样就可以把对象的依赖关系清晰有序的建立起来.

ioc容器解决问题的核心就是把创建和管理对象的控制权从具体的业务对象手中抢过来.由ioc容器来管理对象之间的依赖关系,并由ioc容器完成对象的注入.这样就把应用从复杂的对象依赖关系的管理中解放出来,简化了程序的开发过程.

下图是这个简单ioc容器的类图(原谅我真没学过uml,凑合看吧):

Spring实现一个简单的SpringIOC容器

程序中所有的bean之间的依赖关系我们是放在一个xml文件中进行维护的,就是applicationcontext.xml  

configmanager类完成的功能是读取xml,并将所有读取到有用的信息封装到我们创建的一个map<string,bean>集合中,用来在初始化容器时创建bean对象.

定义一个beanfactory的接口,接口中有一个getbean(string name)方法,用来返回你想要创建的那个对象.

然后定义一个该接口的实现类classpathxmlapplicationcontext.就是在这个类的构造方法中,初始化容器,通过调用configmanager的方法返回的map集合,通过反射和内省一一创建bean对象.这里需要注意,对象的创建有两个时间点,这取决与bean标签中scope属性的值:  

  1. 如果scope="singleton",那么对象在容器初始化时就已创建好,用的时候只需要去容器中取即可.
  2. 如果scope="prototype",那么容器中不保存这个bean的实例对象,每次开发者需要使用这个对象时再进行创建.

使用的主要知识点:

  1. dom4j解析xml文件
  2. xpath表达式(用于解析xml中的标签)
  3. java反射机制
  4. 内省(获取bean属性的set方法进行赋值)

项目结构图及介绍如下:

Spring实现一个简单的SpringIOC容器         

项目需要的jar包与项目结构已经在上图中介绍了,这个项目所能实现的功能如下:

1. ioc容器能管理对象的创建以及对象之间的依赖关系.

2. 能够实现数据的自动类型转换(借助beanutils).

3. 能够实现scope="singleton"和scope="prototype"的功能,即能够控制对象是否为单例.  

下面介绍代码部分:

application.xml:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<beans>
  <bean name="student" class="com.wang.entity.student" >
    <property name="name" value="123"></property>
  </bean>
  
  <bean name="teacher" class="com.wang.entity.teacher">
    <property name="student" ref="student"></property>
  </bean>
  <bean name="person" class="com.wang.entity.person" scope="prototype">
    <property name="teacher" ref="teacher"></property>
    <property name="student" ref="student"></property>
  </bean>
  
</beans>

实体类student,teacher,person:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.wang.entity;
//student类
public class student {
  private string name;
 
  public string getname() {
    return name;
  }
 
  public void setname(string name) {
    this.name = name;
  }
}
/************************************/
package com.wang.entity;
//teacher类
public class teacher {
 
  private student student;
 
  public student getstudent() {
    return student;
  }
 
  public void setstudent(student student) {
    this.student = student;
  }
   
}
/************************************/
package com.wang.entity;
//person类
public class person {
 
  private student student;
  private teacher teacher;
  
  public student getstudent() {
    return student;
  }
  public void setstudent(student student) {
    this.student = student;
  }
  public teacher getteacher() {
    return teacher;
  }
  public void setteacher(teacher teacher) {
    this.teacher = teacher;
  }
}

用于封装bean标签信息的bean类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.wang.config;
 
import java.util.arraylist;
import java.util.list;
 
public class bean {
 
  
  private string name;
  private string classname;
  private string scope="singleton";
  private list<property> properties=new arraylist<property>();
 
  
  public string getscope() {
    return scope;
  }
 
  public void setscope(string scope) {
    this.scope = scope;
  }
 
  public string getname() {
    return name;
  }
 
  public void setname(string name) {
    this.name = name;
  }
 
  public string getclassname() {
    return classname;
  }
 
  public void setclassname(string classname) {
    this.classname = classname;
  }
 
  public list<property> getproperties() {
    return properties;
  }
 
  public void setproperties(list<property> properties) {
    this.properties = properties;
  }
 
  
}

用与封装bean子标签property内容的property类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.wang.config;
 
public class property {
 
  private string name;
  private string value;
  private string ref;
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public string getvalue() {
    return value;
  }
  public void setvalue(string value) {
    this.value = value;
  }
  public string getref() {
    return ref;
  }
  public void setref(string ref) {
    this.ref = ref;
  }
 
  
}

configmanager类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.wang.config.parse;
 
import java.io.inputstream;
import java.util.hashmap;
import java.util.list;
import java.util.map;
 
import org.dom4j.document;
import org.dom4j.documentexception;
import org.dom4j.element;
import org.dom4j.io.saxreader;
import org.junit.test;
 
import com.wang.config.bean;
import com.wang.config.property;
 
public class configmanager {
  
  private static map<string,bean> map=new hashmap<string,bean>();
 
  //读取配置文件并返回读取结果
  //返回map集合便于注入,key是每个bean的name属性,value是对应的那个bean对象
  public static map<string, bean> getconfig(string path){
    /*dom4j实现
     * 1.创建解析器
     * 2.加载配置文件,得到document对象
     * 3.定义xpath表达式,取出所有bean元素
     * 4.对bean元素继续遍历
     *   4.1将bean元素的name/class属性封装到bean类属性中
     *   4.2获得bean下的所有property子元素
     *   4.3将属性name/value/ref分装到类property类中
     * 5.将property对象封装到bean对象中
     * 6.将bean对象封装到map集合中,返回map
      */
    //1.创建解析器
    saxreader reader=new saxreader();
    //2.加载配置文件,得到document对象
    inputstream is = configmanager.class.getresourceasstream(path);
    document doc =null;
    try {
       doc = reader.read(is);
    } catch (documentexception e) {
      e.printstacktrace();
      throw new runtimeexception("请检查您的xml配置是否正确");
    }
    // 3.定义xpath表达式,取出所有bean元素
    string xpath="//bean";
    
    //4.对bean元素继续遍历
    list<element> list = doc.selectnodes(xpath);
    if(list!=null){
      //4.1将bean元素的name/class属性封装到bean类属性中
    
       // 4.3将属性name/value/ref分装到类property类中
      for (element bean : list) {
        bean b=new bean();
        string name=bean.attributevalue("name");
        string clazz=bean.attributevalue("class");
        string scope=bean.attributevalue("scope");
        b.setname(name);
        b.setclassname(clazz);
        if(scope!=null){
          b.setscope(scope);
        }
         // 4.2获得bean下的所有property子元素
        list<element> children = bean.elements("property");
        
         // 4.3将属性name/value/ref分装到类property类中
        if(children!=null){
          for (element child : children) {
            property prop=new property();
            string pname=child.attributevalue("name");
            string pvalue=child.attributevalue("value");
            string pref=child.attributevalue("ref");
            prop.setname(pname);
            prop.setref(pref);
            prop.setvalue(pvalue);
            // 5.将property对象封装到bean对象中
            b.getproperties().add(prop);
          }
        }
        //6.将bean对象封装到map集合中,返回map
        map.put(name, b);
      }
    }
    
    return map;
  }
 
}

 beanfactory接口:

?
1
2
3
4
5
6
package com.wang.main;
 
public interface beanfactory {
  //核心方法getbean
  object getbean(string name);
}

classpathxmlapplicationcontext类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package com.wang.main;
 
import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;
import java.util.hashmap;
import java.util.map;
import java.util.map.entry;
 
import org.apache.commons.beanutils.beanutils;
import org.junit.test;
 
import com.wang.config.bean;
import com.wang.config.property;
import com.wang.config.parse.configmanager;
import com.wang.entity.student;
//import com.wang.utils.beanutils;
import com.wang.utils.beanutil;
 
public class classpathxmlapplicationcontext implements beanfactory {
 
  // 获得读取的配置文件中的map信息
  private map<string, bean> map;
  // 作为ioc容器使用,放置sring放置的对象
  private map<string, object> context = new hashmap<string, object>();
 
  public classpathxmlapplicationcontext(string path) {
    // 1.读取配置文件得到需要初始化的bean信息
    map = configmanager.getconfig(path);
    // 2.遍历配置,初始化bean
    for (entry<string, bean> en : map.entryset()) {
      string beanname = en.getkey();
      bean bean = en.getvalue();
 
      object existbean = context.get(beanname);
      // 当容器中为空并且bean的scope属性为singleton时
      if (existbean == null && bean.getscope().equals("singleton")) {
        // 根据字符串创建bean对象
        object beanobj = createbean(bean);
 
        // 把创建好的bean对象放置到map中去
        context.put(beanname, beanobj);
      }
    }
 
  }
 
  // 通过反射创建对象
  private object createbean(bean bean) {
    // 创建该类对象
    class clazz = null;
    try {
      clazz = class.forname(bean.getclassname());
    } catch (classnotfoundexception e) {
      e.printstacktrace();
      throw new runtimeexception("没有找到该类" + bean.getclassname());
    }
    object beanobj = null;
    try {
      beanobj = clazz.newinstance();
    } catch (exception e) {
      e.printstacktrace();
      throw new runtimeexception("没有提供无参构造器");
    }
    // 获得bean的属性,将其注入
    if (bean.getproperties() != null) {
      for (property prop : bean.getproperties()) {
        // 注入分两种情况
        // 获得要注入的属性名称
        string name = prop.getname();
        string value = prop.getvalue();
        string ref = prop.getref();
        // 使用beanutils工具类完成属性注入,可以自动完成类型转换
        // 如果value不为null,说明有
        if (value != null) {
          map<string, string[]> parmmap = new hashmap<string, string[]>();
          parmmap.put(name, new string[] { value });
          try {
            beanutils.populate(beanobj, parmmap);
          } catch (exception e) {
            e.printstacktrace();
            throw new runtimeexception("请检查你的" + name + "属性");
          }
        }
 
        if (ref != null) {
          // 根据属性名获得一个注入属性对应的set方法
          // method setmethod = beanutil.getwritemethod(beanobj,
          // name);
 
          // 看一看当前ioc容器中是否已存在该bean,有的话直接设置没有的话使用递归,创建该bean对象
          object existbean = context.get(prop.getref());
          if (existbean == null) {
            // 递归的创建一个bean
            existbean = createbean(map.get(prop.getref()));
            // 放置到context容器中
            // 只有当scope="singleton"时才往容器中放
            if (map.get(prop.getref()).getscope()
                .equals("singleton")) {
              context.put(prop.getref(), existbean);
            }
          }
          try {
            // setmethod.invoke(beanobj, existbean);
              //通过beanutils为beanobj设置属性
            beanutils.setproperty(beanobj, name, existbean);
          } catch (exception e) {
            e.printstacktrace();
            throw new runtimeexception("您的bean的属性" + name
                + "没有对应的set方法");
          }
 
        }
 
      }
    }
 
    return beanobj;
  }
 
  @override
  public object getbean(string name) {
    object bean = context.get(name);
    // 如果为空说明scope不是singleton,那么容器中是没有的,这里现场创建
    if (bean == null) {
      bean = createbean(map.get(name));
    }
 
    return bean;
  }
 
}

最后就是一个测试类testbean:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.wang.main;
 
import org.junit.test;
 
import com.wang.entity.person;
import com.wang.entity.student;
import com.wang.entity.teacher;
 
 
public class testbean {
 
  @test
  public void func1(){
    
    beanfactory bf=new classpathxmlapplicationcontext("/applicationcontext.xml");
    person s=(person)bf.getbean("person");
    person s1=(person)bf.getbean("person");
    system.out.println(s==s1);
    system.out.println(s1);
    student stu1=(student) bf.getbean("student");
    student stu2=(student) bf.getbean("student");
    string name=stu1.getname();
    system.out.println(name);
    system.out.println(stu1==stu2);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/fingerboy/p/5425813.html

延伸 · 阅读

精彩推荐