首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 计算机考试 > 认证考试 > JAVA认证 >

简单模拟spring的容器管理bean

2009-02-05 
spring

    package com.spring;
  import java.io.IOException;
  import java.net.URL;
  import java.util.ArrayList;
  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;
  import com.vo.BeanDefinition;
  /**
  * 简单模拟spring的ClassPathXmlApplicationContext spring容器管理bean
  *
  * @author examda
  *
  */
  @SuppressWarnings("unchecked")
  public class MyApplicationContext
  {
  private List<BeanDefinition> list = new ArrayList<BeanDefinition>();
  private Map<String, Object> sigletons = new HashMap<String, Object>();
  public MyApplicationContext(String fileName)
  {
  this.readXML(fileName);
  try
  {
  instanceBeans();
  }
  catch (Exception e)
  {
  e.printStackTrace();
  }
  }
  /**
  * 实例化所有bean
  *
  * @throws InstantiationException
  * @throws IllegalAccessException
  * @throws ClassNotFoundException
  */
  private void instanceBeans() throws InstantiationException,
  IllegalAccessException, ClassNotFoundException
  {
  for (BeanDefinition bean : list)
  {
  if (null != bean.getClassName() && bean.getClassName().length() > 0)
  sigletons.put(bean.getId(), Class.forName(bean.getClassName())
  .newInstance());
  }
  }
  /**
  * 读取xml配置
  *
  * @param fileName
  */
  public void readXML(String fileName)
  {
  SAXBuilder builder = new SAXBuilder();
  URL url = this.getClass().getClassLoader().getResource(fileName);
  try
  {
  Document doc = builder.build(url);
  XPath xpath = XPath.newInstance("//ns:beans/ns:bean");
  xpath.addNamespace("ns",
  "http://www.springframework.org/schema/beans");
  List<Element> beans = xpath.selectNodes(doc);
  for (Element bean : beans)
  {
  String id = bean.getAttributeValue("id");
  String className = bean.getAttributeValue("class");
  BeanDefinition beanDefinition = new BeanDefinition(id,
  className);
  list.add(beanDefinition);
  }
  }
  catch (JDOMException e)
  {
  e.printStackTrace();
  }
  catch (IOException e)
  {
  e.printStackTrace();
  }
  }
  /**
  * 得到指定id的bean
  *
  * @param id
  * @return
  */
  public Object getBean(String id)
  {
  return sigletons.get(id);
  }
  }
  测试:
  @Test
  public void testMyUserService()
  {
  MyApplicationContext ctx = new MyApplicationContext("beans.xml");
  UserService us = (UserService) ctx.getBean("userService");
  us.print();
  }

 

3COME考试频道为您精心整理,希望对您有所帮助,更多信息在http://www.reader8.com/exam/

热点排行