美文网首页从零学Java笔录凯哥Java-工作总结
Java中反射学习系列教程-小案例-模拟spring创建bean

Java中反射学习系列教程-小案例-模拟spring创建bean

作者: 凯哥Java | 来源:发表于2019-06-28 09:18 被阅读0次

    本文是《Java中反射学习系列教程》中的第六篇文章,如果想系统的学习反射技术,建议跟着本教程从第一篇文章开始。本文是《Java中反射学习系列教程》最后一篇文章。在本文中,我们将要做个小案例:模拟基于xml配置的spring创建bean对象

    本文主要内容:

    使用反射模拟spring 基于XML配置获取bean对象并调用方法

    5 四:反射案例

    使用反射模拟spring 基于XML配置获取bean对象并调用方法

    先来看看spring基于XML配置怎么获取bean:

    public static void main(String[] args) {

       ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");

       Person person = (Person)context.getBean("person");

       //TODO......

    }

    Xml中:

    解析思路:

    1:获取指定xml文件进行解析

    2:根据需要的bean的name得到对象全路径

    3:通过反射实例化对象后将对象返回。

    根据以上思路我们自己模拟spring获取bean

    1:创建xml文件:

    在resource下创建application.xml文件。如下图:

    2:对xml进行解析并放入到map中

    3:测试代码调用:

    /**

    * 模拟spring 基于xml配置获取对象

    */

    @Test

    public void refSpringDemoTest(){

       //获取context

     Map<String ,Object> context =   XmlUtils.getBeanMap("application.xml");

       ContextBeanUtils<StudentServiceImpl> beanUtils = new ContextBeanUtils<>();

       StudentServiceImpl studentService = beanUtils.getBean(context,"studentService");

       log.info("调用方法:{}",studentService.getList());

       //获取person对象

       ContextBeanUtils<PersonServiceImpl> serviceContextBeanUtils = new ContextBeanUtils<>();

       PersonServiceImpl personService = serviceContextBeanUtils.getBean("persontService");

       log.info("personService.list:{}",personService.getList());

       log.info("personService.getPersonByName:{}",personService.getPersonByName("sixiaosi"));

    }

    运行结果:

    本系列教程所涉及到的所有相关代码已经发布在git上。欢迎大家下载

    相关文章

      网友评论

        本文标题:Java中反射学习系列教程-小案例-模拟spring创建bean

        本文链接:https://www.haomeiwen.com/subject/wpwdcctx.html