. Today, we write a project to simulate the bean Factory of spring. In spring, we can configure the class to applicationContext. in the xml file, you can then retrieve the objects of this class from beanFactoy. here we need to use xml parsing Technology in java. There are four commonly used parsing technologies, here we use jdom parsing. First, we need to download the jdom jar file at www.jdom.org on the jdom official website, introduce all the jar packages under lib and jdom. jar core jar package introduction is OK. the following code uses the traffic tool interface package com. soukenan. spring. factory; public interface Vehicle {public void run ();} two Vehicle-like package com. soukenan. spring. factory; public class Car implements Ve Hicle {@ Override public void run () {System. out. println ("I have four wheel drives, and I can run very fast,") ;}} train class package com. soukenan. spring. factory; public class Train implements Vehicle {@ Override public void run () {System. out. println ("I Have A Lot Of freelogs. I can run very fast.,") ;}} spring configuration file <? Xml version = "1.0" encoding = "UTF-8"?> <Beans> <bean id = "car" class = "com. soukenan. spring. factory. car "> </bean> <bean id =" train "class =" com. soukenan. spring. factory. train "> </bean> </beans> BeanFactory interface package com. soukenan. spring. factory; public interface BeanFactory {public Object getBean (String id);} implements the ClassPathXmlApplicationContext class package com. soukenan. spring. factory; import java. io. IOException; import java. util. hashMap; import java. util. list; import java. util. map; import org. jdom2.Document; import org. jdom2.Element; import org. jdom2.input. SAXBuilder; import org. jdom2.xpath. XPath; public class ClassPathXmlApplicationContext implements BeanFactory {public Map <String, Object> container = new HashMap <String, Object> (); public ClassPathXmlApplicationContext (String path) throws Exception {SAXBuilder sb = new SAXBuilder (); www.2cto.com Document doc = sb. build (this. getClass (). getClassLoader (). getResourceAsStream (path); Element root = doc. getRootElement (); List list = XPath. selectNodes (root, "/beans/bean"); for (int I = 0; I <list. size (); I ++) {Element bean = (Element) list. get (I); String id = bean. getAttributeValue ("id"); String className = bean. getAttributeValue ("class"); Object o = Class. forName (className ). newInstance (); container. put (id, o) ;}@ Override public Object getBean (String id) {return this. container. get (id) ;}} directory of each file test main class package com. soukenan. spring. factory; import java. io. IOException; import java. util. properties; public class Main {public static void main (String [] args) throws IOException, InstantiationException, IllegalAccessException, Exception {BeanFactory bf = new ClassPathXmlApplicationContext ("applicationContext. xml "); Vehicle v = (Vehicle) bf. getBean ("car"); v. run ();}}