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