java创建子类对象的步骤_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中:

6049dd635e944e0ab3535b2283a4900b

解析思路:

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

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

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

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

1:创建xml文件:

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

ac4c0489271242cba94dc223fbb88dd9

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

8bbeece264a64605abde97a4ef9e7958

3:测试代码调用:

/**

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

*/

@Test

public void refSpringDemoTest(){

//获取context

Map context = XmlUtils.getBeanMap("application.xml");

ContextBeanUtils beanUtils = new ContextBeanUtils<>();

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

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

//获取person对象

ContextBeanUtils serviceContextBeanUtils = new ContextBeanUtils<>();

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

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

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

}

7bd5fb1ef96e406488e2d2ba24b1e2a2

运行结果:

d55add576fe348868779e2ee8b03e31b

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值