简单模拟Spring容器(一)
分类:
版权声明:本文为博主原创文章,未经博主允许不得转载。
本次模拟非常简单,所以直接上代码!
一、配置文件bean.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans>
- <bean id="com.summer.test.Test" class="com.summer.test.Test" name="com.summer.test.Test"></bean>
- </beans>
二、实体类Test
- package com.summer.test;
- public class Test {
- public void test(){
- System.out.println("=======test=========");
- }
- }
三、模拟Spring容器SpringContext
- package com.summer.util;
- 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 com.summer.test.Test;
- /**
- * 自定义Spring容器
- * @author Administrator
- *
- */
- public class SpringContext {
- /**
- * key:为bean的属性ID的值
- * value:为bean的属性class的值
- */
- public static Map<String, Object> map = new HashMap<String, Object>();
- /**
- * 读取配置文件,解析配置文件
- */
- public static void readApplicationContextXml(){
- try {
- SAXReader reader = new SAXReader();
- Document doc = reader.read("bean.xml");
- Element root = doc.getRootElement();
- List<Element> beans = root.elements();
- for (Element bean : beans) {
- String id = bean.attributeValue("id");
- String clazz = bean.attributeValue("class");
- map.put(id, Class.forName(clazz).newInstance());
- }
- } catch (DocumentException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- public static Object getBean(String beanName){
- readApplicationContextXml();
- return map.get(beanName);
- }
- /**
- * 测试
- * @param args
- */
- public static void main(String[] args) {
- Test test = (Test) SpringContext.getBean("com.summer.test.Test");
- test.test();
- }
- }