ClassPathXmlApplicationContext方式读取配置文件

ClassPathXmlApplicationContext方式读取配置文件

  • 读取配置文件内容
  • 将配置文件内容通过反射获取实例对象
  • 将对象实例填充到一个Map中,交给容器统一控制
  • getBean()方法从容器中获取指定实例对象
public interface BeanFactory {
  public Object getBean(String id);
}
 
//实现类ClassPathXmlApplicationContext
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
 
public class ClassPathXmlApplicationContext implements BeanFactory {
   
  private Map<String , Object> beans = new HashMap<String, Object>();
   
  //(IOC:Inverse of Control/DI:Dependency Injection)
  public ClassPathXmlApplicationContext() throws Exception {
    SAXBuilder sb=new SAXBuilder();
     
    Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); //构造文档对象
    Element root=doc.getRootElement(); //获取根元素HD
    List list=root.getChildren("bean");//取名字为disk的所有元素
    for(int i=0;i<list.size();i++){
      Element element=(Element)list.get(i);
      String id=element.getAttributeValue("id");
      String clazz=element.getAttributeValue("class");
      Object o = Class.forName(clazz).newInstance();
      System.out.println(id);
      System.out.println(clazz);
      beans.put(id, o);
       
      for(Element propertyElement : (List<Element>)element.getChildren("property")) {
        String name = propertyElement.getAttributeValue("name"); //userDAO
        String bean = propertyElement.getAttributeValue("bean"); //u
        Object beanObject = beans.get(bean);//UserDAOImpl instance
         
        String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
        System.out.println("method name = " + methodName);
         
        Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
        m.invoke(o, beanObject);
      }     
    }    
  }
 
  public Object getBean(String id) {
    return beans.get(id);
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值