java - spring中加载类的Method声明无法获取
大家讲道理
大家讲道理 2017-04-17 11:04:11
[Java讨论组]

利用spring进行Web开发的时候,发现一个奇怪的问题:

Web容器:tomcat, 版本6.0.20
spring:2.5.6

同样的两个类如下:
类A:

package com.my.company.OneAction;
@Controller
public class OneAction {
    @RequestMapping("/testOne.htm")
    public String service(HttpServletRequest request,ModelMap model) {
        return "/testOne";
    }
}

类B:

package com.my.company.TwoAction;
@Controller
public class TwoAction {
    @Autowired
    private CustomizedService customizedService;

    @RequestMapping(value={"/testTwo.htm"})
    public String service(HttpServletRequest request,ModelMap model) throws Exception {
        // do something
        return "/testTwo";
    }
}

spring在加载的时候,通过默认的DefaultAnnotationHandlerMapping进行Handler注册。其内部实现遍历类的所有方法,匹配@RequestMapping注解。

主要代码:org.springframework.util.ReflectionUtils

public static void doWithMethods(Class targetClass, MethodCallback mc, MethodFilter mf)
            throws IllegalArgumentException {

        // Keep backing up the inheritance hierarchy.
        do {
            Method[] methods = targetClass.getDeclaredMethods();      // 此处出现疑问
            for (int i = 0; i < methods.length; i++) {
                if (mf != null && !mf.matches(methods[i])) {
                    continue;
                }
                try {
                    mc.doWith(methods[i]);
                }
                catch (IllegalAccessException ex) {
                    throw new IllegalStateException(
                            "Shouldn't be illegal to access method '" + methods[i].getName() + "': " + ex);
                }
            }
            targetClass = targetClass.getSuperclass();
        }
        while (targetClass != null);
    }

在targetClass.getDeclaredMethods()返回声明方法时,上述的类AOneAction返回的Method数组为空,即无法找到service方法,而类BTwoAction则可找到service方法,返回长度为1的数组。

自己初步怀疑跟类的加载有关,但无法找到确切的原因,各位能否帮忙给出一些分析意见?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号