手动实现IOC

spring官方实现的ioc是通过反射和xml技术实现的,下面我们可以根据这个思路简单实现一下IOC,此处省略构建项目,项目的整体结构如图

 

 

 第一步,在resources目录下创建beans.xml文件

<beans>
    <bean id="userDao" class="com.grouphy.aop.dao.impl.UserDaoImpl"></bean>
    <bean id="userService" class="com.grouphy.aop.service.impl.UserServiceImpl"></bean>
</beans>

第二步,创建BeanFactory工厂类,这个类的作用就是利用反射和xml技术实现对象的实例化,代码如下

public class BeanFactory {
    private static Map<String,Object> mp = new HashMap<>();

    static{

        try {
            // 1、读取配置文件
            InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
            // 2、解析xml
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(resourceAsStream);
            // 3、编写xpath表达式
            String xpath = "//bean";
            // 4、获取所有签
            List<Element> list = document.selectNodes(xpath);
            // 5、遍历并创建对象实例,设置到map的bean标集合中
            for (Element element : list) {
                String id = element.attributeValue("id");
                String className = element.attributeValue("class");
                Object o = Class.forName(className).newInstance();
                mp.put(id,o);
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }

    public static Object getBean(String userId){
        return mp.get(userId);
    }
}

第三步,编写测试类

public class UserTest {

    @Test
    public void saveTest(){
        IUserService userService = (IUserService) BeanFactory.getBean("userService");
        userService.save(new User());
    }
}

以上就是简单的ioc实现,

详细代码自行拉取:https://gitee.com/duy123456/spring/

 

posted @ 2022-08-23 11:05  码到成功hy  阅读(65)  评论(0编辑  收藏  举报
获取

hahah

name age option