API接口文档,对于Java开发团队来说,是必不可少的一项工作,不管是JSP展示,前后端分离,还是前后端的代码在一个项目中,都是写展示页面必须参考的文档之一。生成接口文档一般有两种方法:
1、手写,费时费力;
2、用第三方插件如Swagger2或自定义注解,但对代码本身入侵严重,所有的接口声明部分都要重新按照它的规范重写。
所以,我打算只通过一个Java函数,在不破坏原有接口代码的基础上,自动生成API文档。直接上代码:
package com.tiger.testApp.controller;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author wh
* @date 2018年8月22日 下午2:17:28
* @Description: 生成API文档
*/
@RestController
@EnableAutoConfiguration
@RequestMapping(value="/api",name="测试生成接口文档")
public class APIDocController {
List<String> classPaths = new ArrayList<String>();
/**
* 获取表名和注释以及表的字段信息
*/
@RequestMapping(value="/list",method=RequestMethod.GET,name="获取表名和注释以及表的字段信息")
public Map<String,Object> list(@RequestParam Map<String,Object> param, Integer pageSize) {
try {
//接口文件包的根路径
String basePack = "com.tiger.testApp.controller";
String classpath = APIDocController.class.getResource("/").getPath();
basePack = basePack.replace(".", File.separator);
String searchPath = classpath + basePack;
List<String> allClasses = new ArrayList<String>();
doPath(new File(searchPath));
for (String s : classPaths) {
s = s.replace(classpath.replace("/","\\").replaceFirst("\\\\",""),"")
.replace("\\",".").replace(".class","");
allClasses.add(s);
}
Map<String,Object> data = new HashMap<String,Object>();
data.put("apiList", getApiInfo(allClasses));
return data;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取指定路径下的所有类名
* @param file
*/
private void doPath(File file) {
if (file.isDirectory()) {
Fil