HandlerMethod方法

134 阅读1分钟

如何在运行时通过 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 实例
        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)

  1. Spring Boot第七弹,别再问我拦截器如何配置了!!!