获取controller中所有接口路径和名称
时间: 2023-11-30 18:05:04 浏览: 25
在Spring MVC中,可以通过扫描@Controller注解或@RequestMapping注解来获取Controller中所有的接口路径和名称。以下是一个获取@Controller中所有接口路径和名称的示例代码:
```java
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Controller
public class EndpointController {
private final RequestMappingHandlerMapping handlerMapping;
public EndpointController(RequestMappingHandlerMapping handlerMapping) {
this.handlerMapping = handlerMapping;
}
@RequestMapping("/endpoints")
public List<Endpoint> endpoints() {
List<Endpoint> endpoints = new ArrayList<>();
Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
RequestMappingInfo mapping = entry.getKey();
HandlerMethod method = entry.getValue();
Class<?> beanType = method.getBeanType();
if (AnnotationUtils.findAnnotation(beanType, Controller.class) != null) {
String name = method.getMethod().getName();
String path = mapping.getPatternsCondition().getPatterns().iterator().next();
endpoints.add(new Endpoint(name, path));
}
}
return endpoints;
}
public static class Endpoint {
private final String name;
private final String path;
public Endpoint(String name, String path) {
this.name = name;
this.path = path;
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
}
}
```
在上面的代码中,我们注入了一个RequestMappingHandlerMapping实例,并且在endpoints()方法中遍历所有的RequestMappingInfo和HandlerMethod,找到所有被@Controller注解的方法,然后获取它们的方法名和路径,并返回一个Endpoint对象列表。最后,我们可以访问"/endpoints"接口来获取所有的接口路径和名称。