java之反射机制从spring配置文件中获取bean对象

导入依赖

<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
<dependency>
    <groupId>org.dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>2.1.1</version>
</dependency>

使用java反射机制来实现从xml配置文件中获取bean对象还原spring获取bean对象方式

通过Dom4j来读取xml中的配置信息,然后动态生成类创建对象 

package demo;

import java.io.IOException;
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;

public class ApplicationContext {
	
	//是缓存Spring容器的Bean对象
	private Map<String,Object> beans=new HashMap<String,Object>();
	/**
	 * 利用配置文件初始化当前容器
	 * 利用xml配置文件初始化全部的bean对象
	 * @throws DocumentException 
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * 
	 */
	public ApplicationContext(String xml) throws DocumentException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException{
		//利用DOM4j读取XML文件
		//解析XML文件内容,得到Bean的类名
		//和Bean的ID,
		//根据类名动态加载类并创建对象
		//将对象和对应的ID添加到map中
		
		//从Resource(classpath中读取流)
		InputStream in =getClass().getClassLoader().getResourceAsStream(xml);
		SAXReader reader = new SAXReader();
		Document doc = reader.read(in);
		in.close();
		//解析xml:<beans><bean>..
		Element root= doc.getRootElement();
		//读取根元素中全部的bean子元素.
		List<Element> list = root.elements("bean");
		for(Element e:list){
			//e就是bean元素 id属性和class属性
			String id = e.attributeValue("id");
			String className = e.attributeValue("class");
			
			//动态加载类,动态创建对象
			Class cls = Class.forName(className);
			Object bean = cls.newInstance();
			beans.put(id, bean);
		}
		
	}
	public Object getBean(String id){
		//根据id在map查找对象,并返回对象A
		return beans.get(id);
	}
	
	//泛型方法:优点是可以减少一次类型转换
	public<T> T getBean(String id,Class<T> cls){
		return (T)beans.get(id);
	}
}

 自定义xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="foo" class="demo.Foo"></bean>
	
	<bean id="date" class="java.util.Date"/>
	
	<bean id="testCase" class="demo.TestCase"/>
	

</beans>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值