spring中加载类的Method声明无法获取
利用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()返回声明方法时,上述的类A
OneAction
返回的Method数组为空,即无法找到service方法,而类B
TwoAction
则可找到service方法,返回长度为1的数组。
自己初步怀疑跟类的加载有关,但无法找到确切的原因,各位能否帮忙给出一些分析意见?
spring-mvc java tomcat javaweb spring
荡漾转转神
10 years, 7 months ago