用jdom(SAXBuilder)解析xml文件,模擬Spring ioc 容器

Spring Bean容器的基本使用(https://blog.csdn.net/qq_39367438/article/details/83901611)

以下是用SAXBuilder解析xml文件,模擬Spring ioc 容器

首先通過maven引入jdom依賴

<dependency>
	<groupId>jdom</groupId>
	<artifactId>jdom</artifactId>
	<version>1.1</version>
</dependency>

beans.xml中

<?xml version="1.0" encoding="UTF-8"?>
	<!-- 用於模擬ClassPathXMLApplicationContext -->
<beans>
	<!-- 自定義標籤
		bean  	 : 容器
		id    	 : 標識符
		class 	 : 具體類的路徑
		property : 類屬性
		name  	 : 屬性名
		value	 : 屬性值
		ref	 	 : 傳入bean
		
		 -->
	<bean id="bookDao" class="com.ss.dao.BookDaoImpl"> 
		<property name="name" value="阿大"/>
		<property name="age" value="100"/>
	</bean>
	
	<bean id="bookService" class="com.ss.service.bookService">
		<property name="bookDao" ref="bookDao"/>
	</bean>
	
</beans>

兩個模擬的具體類
bookDao和bookService

接口

package com.ss.dao;

public interface BookDao {
	
}

package com.ss.dao;

public class BookDaoImpl implements BookDao{
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "BookDaoImpl [name=" + name + ", age=" + age + "]";
	}
	public BookDaoImpl(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	public BookDaoImpl() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	
}

package com.ss.service;

import com.ss.dao.BookDao;

public class BookService {
	private BookDao bookDao;

	public BookDao getBookDao() {
		return bookDao;
	}

	public void setBookDao(BookDao bookDao) {
		this.bookDao = bookDao;
	}

	@Override
	public String toString() {
		return "BookService [bookDao=" + bookDao + "]";
	}

	public BookService(BookDao bookDao) {
		super();
		this.bookDao = bookDao;
	}

	public BookService() {
		super();
		// TODO Auto-generated constructor stub
	}
	
}

ApplicationContext接口

package com.ss.simulation;

public interface ApplicationContext {
	Object getBean(String id);
}


package com.ss.simulation;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class ClassPathXMLApplicationContext implements ApplicationContext {
	//存放對象的集合
	private Map<String, Object> container = new HashMap<>();
	
	/**
	 * 獲取容器
	 * @return
	 */
	public Map<String, Object> getContainer() {
		return container;
	}

	public void setContainer(Map<String, Object> container) {
		this.container = container;
	}

	@Override
	public Object getBean(String id) {
		return container.get(id);
	}
	
	
/**
 * 構造器傳入xml,用反射創建對象,注入容器
 * @param path
 */
	public ClassPathXMLApplicationContext(String path) {
		SAXBuilder builder = new SAXBuilder();

		Document document = null;

		try {
			document = builder.build(ClassPathXMLApplicationContext.class.getClassLoader().getResourceAsStream(path));
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 獲取root根元素
		Element root = document.getRootElement();
		//獲取bean元素
		List<Element> children = root.getChildren("bean");
		for (Element child : children) {
			
			// 獲取標識符和具體類
			String key = child.getAttributeValue("id");
			String classStr = child.getAttributeValue("class");

			try {
			// 通過反射創建對象,放入集合
				Object value = Class.forName(classStr).newInstance();
				container.put(key, value);
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		for (Element child : children) {
			Object obj = container.get(child.getAttribute("id"));
			// 獲取property
			List<Element> properties = child.getChildren("property");

			try {
				for (Element property : properties) {
					/**
					 * ref : bean
					 * setStr : 拼接setter方法名
					 * setter : set方法
					 */
					String ref = property.getAttributeValue("ref");
					String setStr = "";
					Object value = null;
					Method setter = null;
					if (ref != null) {
						setStr = "set".concat(ref.substring(0, 1).toUpperCase()).concat(ref.substring(1));
						System.out.println("ref : " + ref);
						value = container.get(ref);
						setter = obj.getClass().getMethod(setStr, value.getClass().getInterfaces()[0]);

					}else{
						String name = property.getAttributeValue("name");
						setStr = "set".concat(name.substring(0,1).toUpperCase().concat(name.substring(1)));
						try {
							Field field = obj.getClass().getDeclaredField(name);
							
							String stringValue = property.getAttributeValue("value");
							setter = obj.getClass().getDeclaredMethod(setStr, field.getType());
							System.out.println("type : " + field.getType().getName());
							if(field.getType().getName().endsWith("Integer")){
								Integer v = Integer.parseInt(stringValue);
								setter.invoke(obj, v);
							}else if(field.getType().getName().endsWith("String")){
								setter.invoke(obj, stringValue);
							}
						} catch (NoSuchFieldException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						
					}

				}
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章