Spring容器是怎样管理bean的呢?
我们模拟Spring容器的内部实现:
(1) 读取Spring中的Bean配置文件
//读取bean配置文件 public void readXml(String beanDir){ Document document = null; try{ SAXReader sx = new SAXReader(); URL xmlPath = this.getClass().getClassLoader().getResource(beanDir); document = sx.read(xmlPath); MapnsMap = new HashMap (); nsMap.put("ns", "http://www.springframework.org/schema/beans"); XPath xp = document.createXPath("//ns:beans/ns:bean"); xp.setNamespaceURIs(nsMap);//设置命名空间 List el = xp.selectNodes(document);//获取文档下的所有节点 for(Element element:el){ String id = element.attributeValue("id"); String className = element.attributeValue("class"); PeopleBean peopleBean = new PeopleBean(id,className); list.add(peopleBean); } }catch(Exception e){ e.printStackTrace(); } }
2、实例化bean
包含上部分的完整的代码为:
package junit.test;import java.io.StringReader;import java.net.URL;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.XPath;import org.dom4j.io.SAXReader;public class LearnCreateBean { //bean数组 private Listlist = new ArrayList (); private Map
3、 测试
@Test public void test() { //实例化Spring容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); PeopleService peopleService = (PeopleService)ctx.getBean("peopleService"); peopleService.testBeans(); //采用自定义的类来实例化bean LearnCreateBean ctxd = new LearnCreateBean("bean.xml"); PeopleService peopleServiced = (PeopleService)ctx.getBean("peopleService"); peopleService.testBeans(); }
可以发现两者都实现了正确的输出。