1. 程式人生 > >手寫ioc、看這裡有你想要的~!

手寫ioc、看這裡有你想要的~!

public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
         //1、讀取xml配置檔案
        // 獲取xml解析器
        SAXReader saxReader = new SAXReader();
         // 獲得document物件
        Document read = saxReader.read(this.getClass().getClassLoader().getResourceAsStream(xmlPath));
         // 獲得根節點
        Element rootElement = read.getRootElement();
        System.out.println("根節點的名稱: " +rootElement.getName());
         //獲得元素物件
        List<Element> elements = rootElement.elements();
        Object obj = null;
         for (Element sonEle : elements) {
             //2、獲取到每個bean配置,獲得class地址
            //獲得每個bean配置 獲取class地址
            String sonBeanId = sonEle.attributeValue("id");//user1 user2
             if(!beanId.equals(sonBeanId)){
                 continue;
             }
             String beanClassPath = sonEle.attributeValue("class");//com.wangys.reflect.UserEntity
             //3、拿到class地址,進行反射技術例項化物件,使用反射api為私有屬性賦值
            Class<?> forName = Class.forName(beanClassPath);//new UserEntity()
             obj = forName.newInstance();//new UserEntity()
             System.out.println(obj+"!@");
             //拿到成員屬性
            List<Element> sonSoneleme = sonEle.elements();
             for (Element element : sonSoneleme) {
                 String name = element.attributeValue("name");//王永生
                 System.out.println(name+"~~");
                 String value = element.attributeValue("value");//0001
                 System.out.println(value+"~~");
                 //使用反射技術為私有屬性賦值
                 Field declaredField = forName.getDeclaredField(name);//獲得entity欄位 username userid
                 //執行往私有屬性賦值
                 System.out.println(declaredField+"!!!");
                 declaredField.setAccessible(true);
                 declaredField.set(obj, value);
             }
         }
         return obj;
     }
     public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, DocumentException {
         ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");
         UserEntity user = (UserEntity) classPathXmlApplicationContext.getBean("user1");
         System.out.println(user.getUserId() + "---" +user.getUserName());
     }
}