我是靠谱客的博主 舒心犀牛,这篇文章主要介绍简单实现Spring IOC (单例模式)(解析XML方式),现在分享给大家,希望可以做个参考。

基于XML方式的依赖注入,主要是基于XML的解析类的反射机制 

主要思路:

           1、解析xml文件

           2、获取xml文件所有的节点内容

           3、根据类路径反射类

           4、注入属性信息

项目基本框架:

1、首先创建普通maven项目,导入dom4j、Spring context等的依赖

pom.xml(我直接复制的,所以spring的基本依赖基本都有,可以自己选择性导入)

复制代码
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring.xml</groupId> <artifactId>ioc</artifactId> <version>1.0-SNAPSHOT</version> <name>ioc</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <!--定义Spring版本号--> <org.springframework.version>4.3.7.RELEASE</org.springframework.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- spring start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument-tomcat</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- spring end --> </dependencies> <build> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>

2、创建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
package com.spring.xml.bean; public class Car { private String name; private int price; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Car{" + "name='" + name + ''' + ", price=" + price + '}'; } }

 3、创建applicationContext.xml

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="car" class="com.spring.xml.bean.Car"> <property name="name" value="BMW"/> <property name="price" value="100"/> </bean> <bean id="car1" class="com.spring.xml.bean.Car"> <property name="name" value="ChangCheng"/> <property name="price" value="101"/> </bean> </beans>

4、创建类XmlApplicationContext

复制代码
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package com.spring.xml.utils; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.FileNotFoundException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; /** * 1、解析xml文件 * 2、获取xml文件所有的节点内容 * 3、根据类路径反射类 * 4、注入属性信息 */ public class XmlApplicationContext { // xml路径 private String xmlPath; // 存放bean private Map<String, Object> map = null; // 存放从xml解析出来的类的需要注入的属性名和属性值 private List<String> propertyName = new ArrayList<>(); private List<Object> propertyData = new ArrayList<>(); public XmlApplicationContext(String xmlPath) { this.xmlPath = xmlPath; try { getAllElements(); } catch (Exception e) { e.printStackTrace(); } } // 1、读取xml文件,返回根节点 public Iterator readXML() throws DocumentException, FileNotFoundException { SAXReader reader = new SAXReader(); File file = ResourceUtils.getFile("classpath:" + xmlPath); Document document = reader.read(file); Element rootElement = document.getRootElement(); Iterator iterator = rootElement.elementIterator(); return iterator; } // 2、获取xml文件所有的节点内容 public void getAllElements() throws Exception { Iterator iterator = readXML(); List<Class> classList = new ArrayList<>(); List<String> idList = new ArrayList<>(); Class clazz = null; while (iterator.hasNext()) { Element bean = (Element) iterator.next(); //System.out.println(next.getName()) // 获取bean的id,class Iterator beanAttributes = bean.attributeIterator(); String id = null; while (beanAttributes.hasNext()) { Attribute attribute = (Attribute) beanAttributes.next(); String classPropertyName = attribute.getName(); String className = (String) attribute.getData(); if (classPropertyName.equals("class")) { clazz = Class.forName(className); } else id = className; } // System.out.println(id); idList.add(id); // 获取类的属性 Iterator properties = bean.elementIterator(); while (properties.hasNext()) { Element element = (Element) properties.next(); Iterator propertyAttributes = element.attributeIterator(); while (propertyAttributes.hasNext()) { Attribute attribute = (Attribute) propertyAttributes.next(); String attributeName = attribute.getName(); Object attributeData = attribute.getData(); propertyName.add(attributeName); propertyData.add(attributeData); } } classList.add(clazz); } setBeanMap(idList, classList); } // 反射,依赖注入 public Object[] getClass(List<Class> classList) throws Exception { Object[] objects = new Object[classList.size()]; int i = 0; int j = 0; for (Class clazz : classList) { Object o = clazz.newInstance(); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { String methodName = method.getName(); //System.out.println(methodName); if ("set".equals(methodName.substring(0, 3))) { String name = propertyName.get(i); Object data = propertyData.get(i); String field = (String) data; if (name.equals("name")) { data = "set" + ((String) data).substring(0, 1).toUpperCase() + ((String) data).substring(1, ((String) data).length()); } else if (name.equals("value")) { } else continue; String name1 = propertyName.get(i + 1); Object data1 = propertyData.get(i + 1); // 依赖注入 if (methodName.equals(data)) { Field field1 = clazz.getDeclaredField(field); Class<?> type = field1.getType(); String typeName = type.getName(); if ("int".equals(typeName)) data1 = Integer.valueOf((String) data1); method.invoke(o, data1); } i += 2; } } objects[j] = o; j++; //System.out.println(o); } return objects; } public void setBeanMap(List<String> idList, List<Class> classList) throws Exception { map = new HashMap<>(); Object[] objects = getClass(classList); for (int i = 0; i < objects.length; i++) { map.put(idList.get(i), objects[i]); } } public Object getBean(String beanName) { if (!map.isEmpty()) return map.get(beanName); return null; } public Map getBeanMap() { return map; } }

5、主类

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.spring.xml; import com.spring.xml.bean.Car; import com.spring.xml.utils.XmlApplicationContext; import java.util.Map; /** * Hello world! */ public class App { public static void main(String[] args) { XmlApplicationContext context = new XmlApplicationContext("applicationContext.xml"); Car car = (Car)context.getBean("car"); System.out.println(car); Map map = context.getBeanMap(); System.out.println(map); } }

6、结果

最后

以上就是舒心犀牛最近收集整理的关于简单实现Spring IOC (单例模式)(解析XML方式)的全部内容,更多相关简单实现Spring内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(82)

评论列表共有 0 条评论

立即
投稿
返回
顶部