关于通过反射实例化对象的坑

T serviceClass=xxx.Class.newInstance();
Method xxxMethod = serviceClass.getMethod(methodName, requestClass);
Object xxx = xxxMethod.invoke(serviceInstance, request);

以上代码可以实例化成功,但是调用的时候则可能会出现nullPointerException,原因是通过此方式实例化的对象的依赖对象没有注入,如其调用的mapper.java等。

 

解决方案:

@Autowired
private ApplicationContext applicationContext;

T serviceInstance = (T) applicationContext.getBean(xxxClass);

 

posted @ 2021-01-22 11:26  机械公敌  阅读(100)  评论(0编辑  收藏  举报