1.简介
因为做了RBAC结构的权限模型,又懒得写管理界面,就直接一网打尽,写一个获取所有url路径和swagger文档注解的方法,然后百度了下,大部分都是只获取URL接口路径,我拓展了下,可以加上方法的注解参数。
swagger注解可以换成自定义的注解,很简单的,注释里有体现。
2.代码
@Autowired
private WebApplicationContext applicationContext;
@RequestMapping(value = "getAllUrl")
public Object getAllUrl() throws ClassNotFoundException {
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> mappingHandlerMethods = mapping.getHandlerMethods();
List<UrlDesc> list = new ArrayList();
for (Map.Entry<RequestMappingInfo, HandlerMethod> map : mappingHandlerMethods.entrySet()) {
UrlDesc urlDesc = new UrlDesc();
RequestMappingInfo info = map.getKey();
HandlerMethod method = map.getValue();
PatternsRequestCondition patternsCondition = info.getPatternsCondition();
String className = method.getMethod().getDeclaringClass().getName();
/**
* 匹配包路径 根据自己的路径替换
*/
if (className.contains("com.com.controller")) {
//获取类对象
Class clazz = Class.forName(method.getMethod().getDeclaringClass().getName());
String metName = method.getMethod().getName();
/**
* 因为单独获取一个类对象要指定参数,不适合批量使用,所以获取所有的方法然后根据name筛选
*/
Method[] clazzDeclaredMethods = clazz.getDeclaredMethods();
Arrays.stream(clazzDeclaredMethods).forEach(
c -> {
if(c.getName().equals(metName)){
/* swagger注解 可以换成别的 */
ApiOperation annotation = c.getAnnotation(ApiOperation.class);
if(null != annotation){
urlDesc.setDesc(annotation.value());
}
}
}
);
for(String url : patternsCondition.getPatterns()) {
urlDesc.setUrl(url);
}
list.add(urlDesc);
}
}
return list;
}
实体类
@Data
public class UrlDesc implements Serializable,Cloneable {
private static final long serialVersionUID = 1L;
/**
* 路径
*/
private String url;
/**
* 描述
*/
private String desc;
}