模拟spring的注入和读取配置文件(ApplicationContext.xml)

Spring的配置文件(applicationContext.xml)

 

<?xml version="1.0" encoding="UTF-8"?>

<beans>

<bean id="v" class="tfq.factory.spring.Tain">

</bean>

</beans>

 

 

//Bean工厂接口

 

public interface BeanFactory {

 

Object getBean(String id);

}

 

注意要导入spring的jar包和jdom的jar包!

 

import java.io.IOException;
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;
import org.jdom.xpath.XPath;
public class ClassPathXmlApplicationContext implements BeanFactory {
/**
* Spring容器概念
*/
private Map<String,Object> container=new HashMap<String,Object>();
public ClassPathXmlApplicationContext(String fileName)
throws JDOMException, IOException, 
InstantiationException, IllegalAccessException,
ClassNotFoundException {
//实例化一个读取Xml文件对象实例
SAXBuilder sb = new SAXBuilder();
//获取配置文件对象
Document doc = sb.build(this.getClass().getClassLoader()
.getResourceAsStream(fileName));
//获取配置文件中的根节点
Element root = doc.getRootElement();
//获取根节点的子节点
List list = XPath.selectNodes(root, "/beans/bean");
System.out.println(list.size());
//遍历获取的子节点
for (int i = 0; i < list.size(); i++) {
//获取配置文件中的第i个bean节点
Element bean = (Element) list.get(i);
//获取配置文件中的第i个bean节点的ID
String id = bean.getAttributeValue("id");
//获取配置文件中的第i个bean节点class
String cla = bean.getAttributeValue("class");
//获取配置文件中的第i个bean节点class转换成Object
Object o=Class.forName(cla).newInstance();
container.put(id, o);
System.out.println(id + "  " + cla);
}
   }
@Override
public Object getBean(String id) {
return container.get(id);
}
}
import tfq.factory.spring.Moveable;
public class Car implements Moveable{
@Override
public void run(){
System.out.println("Car drive....");
}
}
import java.io.IOException;
import java.util.Properties;
import org.jdom.JDOMException;
public class TestSpring {
public static void main(String[] args) throws ClassNotFoundException,
JDOMException, IOException, InstantiationException, IllegalAccessException{
BeanFactory  f=(BeanFactory)new
 ClassPathXmlApplicationContext("tfq/factory/spring/applicationContext.xml");
Object o=f.getBean("v");
Moveable m=(Moveable)o;
m.run();
}
}
输出:
1
v  tfq.factory.spring.Car
Car drive

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值