项目上需要导出所有接口方法上自定义注解中的值,犯了难。一般我们都是通过fIlter,inteceptor,aop中拦截请求进而可以获取的类的信息。这样可能需要调用多次才能得到我们要的数据。这次给大家分享一下可以一次性获取的方案。不多说,直接上代码:
@Controller
@RequestMapping(value = "/api")
public class TestController {
@Autowired
private WebApplicationContext applicationContext;
@ResponseBody
@RequestMapping(value = "/getAllUrl", method = RequestMethod.GET)
public List getAllUrl() {
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
// 获取url与类和方法的对应信息
Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
Map<String, String> map1 = new HashMap<String, String>();
RequestMappingInfo info = m.getKey();
HandlerMethod method = m.getValue();
//获取当前方法所在类名
Class<?> bean = method.getBeanType();
//获取方法上注解以及注解值
OperationLog methodAnnotation = method.getMethodAnnotation(OperationLog.class);
if(methodAnnotation==null){
continue;
}
String privilegeName = methodAnnotation.tag()+"_"+methodAnnotation.type();
PatternsRequestCondition p = info.getPatternsCondition();
for (String url : p.getPatterns()) {
map1.put("url", url);
}
map1.put("className", method.getMethod().getDeclaringClass().getName()); // 类名
map1.put("method", method.getMethod().getName()); // 方法名
map1.put("tag", privilegeName);
list.add(map1);
}
return list;
}
}