问题:
在Service层反射调用其他Service层的方法 , 调试时发现原先@Autowired注入的Dao层为null。
原因:
这是因为反射获得的类没有交给Spring容器管理,以至于@Autowired失效。
修改前的代码:
private String getResult(String methodParam, String methodName) throws Exception {
Class<BatchWaybillServiceImpl> batchWaybillServiceClass = BatchWaybillServiceImpl.class;
Method method = batchWaybillServiceClass.getDeclaredMethod(methodName, String.class);
method.setAccessible(true); //允许访问私有的方法
BatchWaybillServiceImpl batchWaybillService = new BatchWaybillServiceImpl();
String result = (String) method.invoke(batchWaybillService, methodParam);
return result;
}
修改后的代码,这里将getResult这个方法也放进工具类了:
public static String getResult(String className, String methodName, String methodParam) throws Exception {
Class<?> c = Class.forName(className);
Object bean = getBean(c); //获取要创建的bean
Method method = c.getDeclaredMethod(methodName, methodParam.getClass()); //getDeclaredMethod能找到所有的方法
method.setAccessible(true); //允许访问私有的方法
return (String) method.invoke(bean, methodParam);
}
解决问题的过程中参考这位大哥的文章:
跳转文章