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

本文是《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上。欢迎大家下载

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容