最近使用反射获取对象,并调用方法时,无法获取到spring中自动注入的对象。
Class<?> cls = Class.forName(className);
Object obj = cls.newInstance();
Method method = cls.getDeclaredMethod(methodName, Integer.class);
method 为Service里的方法,Service中注入了Dao层对象,反射调用此方法是,没有正确获取注入对象,即spring实例没有生效。故调整思路,用Spring中getBean的方式获取实例。
//获取当前上下文环境,spring容器
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
//获取类实例
Class<?> cls = wac.getBean(className).getClass();
//获取执行方法
Method m = cls.getDeclaredMethod(methodName,Integer.class);
正解。
网友评论