ioc容器简单模拟

ioc容器简单模拟,第1张

ioc容器简单模拟

        
            org.dom4j
            dom4j
            2.1.1
        
        
            jaxen
            jaxen
            1.1.1
        
    
public interface ApplicationContext {
    public Object getBean(String beanId);
}
public class ClassPathXmlApplicationContext implements ApplicationContext{
    private Map iocContet = new HashMap();
    public ClassPathXmlApplicationContext(){
        try{
            String filePath = this.getClass().getResource("/applicationContext.xml").getPath();
            filePath = new URLDecoder().decode(filePath, "UTF-8");
            SAXReader reader = new SAXReader();
            document document = reader.read(new File(filePath));
            List bean = document.getRootElement().selectNodes("bean");
            for (Node node : bean){
                Element ele = (Element) node;
                String id = ele.attributevalue("id");
                String className = ele.attributevalue("class");
                Class c = Class.forName(className);
                Object obj = c.newInstance();
                List properties = ele.selectNodes("property");
                for (Node p : properties){
                    Element property = (Element) p;
                    String propName = property.attributevalue("name");
                    String propValue = property.attributevalue("value");
                    String setMethodName = "set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
                    System.out.println("准备执行" + setMethodName + "方法注入数据");
                    Method setMethod = c.getMethod(setMethodName, String.class);
                    setMethod.invoke(obj, propValue);

                }
                iocContet.put(id, obj);

            }
            System.out.println(":ioc容器初始化完毕");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public Object getBean(String beanId) {

        return iocContet.get(beanId);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5619364.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存