如何在运行时通过 HandlerMethod 获取处理器方法的声明类
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.lang.reflect.Method;
import java.util.Map;
public class HandlerMethodDetailsExample {
public static void main(String[] args) {
RequestMappingHandlerMapping handlerMapping = ...;
Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
RequestMappingInfo mappingInfo = entry.getKey();
HandlerMethod handlerMethod = entry.getValue();
Class<?> declaringClass = handlerMethod.getBeanType();
Method method = handlerMethod.getMethod();
MethodParameter[] parameters = handlerMethod.getMethodParameters();
MethodParameter returnType = handlerMethod.getReturnType();
System.out.println("Mapping: " + mappingInfo);
System.out.println("Declaring Class: " + declaringClass.getName());
System.out.println("Handler Method: " + method);
System.out.println("Method Parameters:");
for (MethodParameter parameter : parameters) {
System.out.println(" - " + parameter.getParameterName() + ": " + parameter.getParameterType().getName());
}
System.out.println("Return Type: " + returnType.getParameterType().getName());
}
}
}
相关链接
1. spring注解工具类AnnotatedElementUtils和AnnotationUtils
2.Java 注解(Annotation)
- Spring Boot第七弹,别再问我拦截器如何配置了!!!