首页 > 技术文章 > BeanFactory 工厂模式

brucetie 2018-01-09 14:32 原文

 

/**
 * BeanFactory实现类
 */
public class ClassPathXmlApplicationContext implements BeanFactory {
    
    private Map<String, Object> map = new HashMap<String, Object>();
    
    @SuppressWarnings("unchecked")
    public ClassPathXmlApplicationContext(String fileName) throws DocumentException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        
         //加载配置文件
         SAXReader reader = new SAXReader(); 
         Document document = reader.read(ClassPathXmlApplicationContext.class.getClassLoader().getResourceAsStream(fileName));
         
         //获取根节点
         Element root = document.getRootElement(); 
         //获取子节点
         List<Element> childElements = root.elements();
         
         for (Element element : childElements) {
             map.put(element.attributeValue("id"), Class.forName(element.attributeValue("class")).newInstance());
         }
    }

    @Override
    public Object getBean(String id) throws ExecutionException {
        return map.get(id);
    }

}

 

参考:https://www.cnblogs.com/hongwz/p/5941118.html

推荐阅读