java反射使spring依赖注入和AOP失效

因为我们是手动通过反射获得的Bean的实例,这种方式相当于我们new Bean(),此Bean的实例已完全脱离Spring容器,所以Spirng无法感知它的存在,所以调用类中的依赖注入类和AOP会失效

解决方法:以下均为局部核心代码,需要根据自己场景相应调整

1:

WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
Class clazz = wac.getBean("XService").getClass();
Method method = clazz.getDeclaredMethod(methodName);
method.invoke(wac.getBean("XService"));

2:

@Autowired
private ApplicationContext applicationContext;

Class serviceClazz = Class.forName(serviceName);
Class paramClazz = Class.forName(paramName);

Method method = serviceClazz.getMethod(methodName, paramClazz);
method.invoke(applicationContext.getBean(serviceClazz), paramObj);

3:多参数反射

Class serviceClazz = Class.forName(serviceName);
List paramList = new ArrayList<>();
List> paramClazzList = new ArrayList<>();
for (Object o : params) {
    Class paramClazz = o.getClass();
    paramList.add(o);
    paramClazzList.add(paramClazz);
}
Method method = serviceClazz.getMethod(methodName, paramClazzList.toArray(new Class[]{}));
method.invoke(applicationContext.getBean(serviceClazz), paramList.toArray()); 
  

 

你可能感兴趣的:(Java)