java反射遇上spring注入@Autowired

本文介绍了一种使用Spring框架时遇到的问题,即通过反射调用自动注入的Bean时出现null的情况,并给出了具体的解决方案。文章详细解释了问题的原因在于Spring默认的单例模式,并提供了一个通过ContextLoader获取当前Web应用上下文来正确调用Bean的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

昨天因为写某个功能用到了反射,写完之后,运行报错:XXXXService is null
仔细一看,才发现这个为null的XXXXService是自动注入的,Spring默认产生的bean是单例的。。。。。。

之前的反射代码

XService xService = new XService();
Class c = xService.getClass();
Method m = c.getDeclaredMethod(methodName);
return m.invoke(xService);

XService中有这样一行代码

@Autowired
private XXXXService xxxxService;

XService的methodName方法中调用了xxxxService的方法,最终就运行报错了

反射代码修改为

WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
Class cls = wac.getBean("XService").getClass();
Method m = cls.getDeclaredMethod(methodName);
return m.invoke(wac.getBean("XService"));

这样就好了,^_^

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值