昨天因为写某个功能用到了反射,写完之后,运行报错: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"));
这样就好了,^_^