美文网首页
java反射调用Service中方法

java反射调用Service中方法

作者: 1601 | 来源:发表于2018-05-06 02:28 被阅读1009次

    最近使用反射获取对象,并调用方法时,无法获取到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);
    

    正解。

    相关文章

      网友评论

          本文标题:java反射调用Service中方法

          本文链接:https://www.haomeiwen.com/subject/qusyrftx.html