注釋vs注解
在進行接口開發時,我們通常會使用swagger生成接口文檔。為了讓使用者能更好的使用文檔,就要使用注解標記每個接口的名稱,參數說明。比如以下代碼:
@Api(tags = "學生接口")
@RestController
@RequestMapping("web/v1/student")
public class StudentController {
@ApiOperation("根據編號獲取學生信息")
@ApiImplicitParams(
@ApiImplicitParam(name = "stu_no", value = "學生編號"))
@GetMapping("getByNo")
public StudentVO getByNO(@RequestParam("stu_no") String stuNo) {
StudentVO stu = new StudentVO();
stu.setStuNo(stuNo);
stu.setName("張三");
return stu;
}
@ApiOperation("添加學生信息")
@ApiImplicitParams(
{
@ApiImplicitParam(name = "name", value = "學生名稱", defaultValue = "張三"),
@ApiImplicitParam(name = "no", value = "學生編號", defaultValue = "std-10001", required = true)
}
)
@PostMapping("add")
public StudentVO addStudent(String name, String no) {
StudentVO s = new StudentVO();
s.setName(name);
s.setStuNo(no);
return s;
}
}
在實際開發中,需要用各種注解表示接口功能。尤其是接口參數,我們需要用@ApiImplicitParam
依次標記每個參數,這種工作往往單調重復,而且還會使我們的業務代碼更加復雜。
那我們能不能使用更簡單的方式定義文檔呢?在平常開發中,我們會對我們的一些代碼添加上注釋來說明某些功能。通過/** */
可以注釋一個Class
類,或者一個方法,同時在注釋中使用@param
來說明某個參數的具體含義。這種方式看起來更加簡潔明了,比如如下Controller
類:
/**
* 學生接口
*/
@RestController
@RequestMapping("web/v1/student")
public class StudentController {
/**
* 根據編號獲取學生信息
* @param stuNo 學生編號
*/
@GetMapping("getByNo")
public StudentVO getByNO(@RequestParam("stu_no") String stuNo) {
StudentVO stu = new StudentVO();
stu.setStuNo(stuNo);
stu.setName("張三");
return stu;
}
/**
* 添加學生信息
* @param name 學生名稱|張三
* @param no 學生編號|required|std-10001
*/
@PostMapping("add")
public StudentVO addStudent(String name, String no) {
StudentVO s = new StudentVO();
s.setName(name);
s.setStuNo(no);
return s;
}
}
不需要用更多的注解,只需給我們的類和方法加上注釋就能生成文檔豈不是更香么。
實現方式
Swagger2Controller
我們通過http://localhost:8080/swagger-ui.html
查看接口文檔時,可以查看到下面的api-docs
的ajax
請求,里面包含了所有的接口信息。
它對應的
Controller
為Swagger2Controller
DocumentationCache
通過debug調試獲取請求api-docs
接口時的相關信息可以找到關鍵的DocumentationCache
類,里面存儲了文檔的所有信息。最終swagger文檔信息是通過它生成的。
所以我們只需修改DocumentationCache
就能修改swagger的文檔信息。通過源碼可以發現DocumentationCache
對象是通過依賴注入賦值的。所以我們也可以通過@Autowired
等注解獲取它。
@EnableEasySwagger
為了能夠配置方便,我們使用一個@EnableEasySwagger
注解開啟注釋生成文檔功能。
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Import({EasySwaggerConfig.class})
@Documented
public @interface EnableEasySwagger {
}
我們使用EasySwaggerConfig
IOC注入保存DocumentationCache
實例,同時還需要WebApplicationContext
這個類來獲取所有的Controller
信息。
@Configuration
public class EasySwaggerConfig {
@Autowired
DocumentationCache documentationCache;
@Autowired
WebApplicationContext applicationContext;
public EasySwaggerConfig() {
}
@Bean
Swagger2Hook provideInit() {
return new Swagger2Hook(documentationCache, applicationContext);
}
}
核心邏輯在Swagger2Hook
中。
WebApplicationContext獲取Controller信息
我們需要通過WebApplicationContext
獲取所有的Controller
信息,如類名,請求接口地址等。然后更加類名掃描工程源碼目錄。因為注釋信息是無法編譯到class文件的,所以就需要讀取工程目錄中的源碼文件,依次遍歷每個Controller
中的注釋信息。
/**
* 獲取所有url
*/
private void scanAllUrl() {
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
// 獲取url與類和方法的對應信息
Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
for (RequestMappingInfo req : map.keySet()) {
HandlerMethod hm = map.get(req);
String url = req.getPatternsCondition().getPatterns().iterator().next();
String className = hm.getBeanType().getName();
ApiDoc apiDoc = new ApiDoc();
apiDoc.controllerClass = className;
controllerClasses.add(className);
apiDoc.methodName = hm.getMethod().getName();
docInfo.apiMap.put(url, apiDoc);
}
if (hasSrc) scanControllerDoc();
}
讀取Controller源碼中注釋,方法信息
/**
* 掃描controller文檔
*/
private void scanControllerDoc() {
for (String cls : controllerClasses) {
File sourceFile = getSourceFile(projectDir, cls);
if (sourceFile != null) {
parseControllerDoc(sourceFile, cls);
}
}
}
private static final String DOC_START = "^\\s*(/\\*\\*)$";
private static final String DOC_END = "^\\s*\\*/$";
private static final String DOC_CLASS = "^.* *class .+$";
private static final String DOC_METHOD_KT = "^\\s*fun (\\S*)\\(.*$";
private static final String DOC_METHOD_JAVA = "^\\s*public \\S+ (\\S*)\\(.*$";
private static final String DOC_PARAMS = "^\\s*\\* @param\\s+(.*)$";
private static final String DOC_FIELD_JAVA = "^\\s*(public|private) \\S+ (\\S+);\\s*//(\\S+)$";
private static final String DOC_FIELD_KT = "^\\s*(var|val) (\\S+):.*//(\\S+)$";
private void parseControllerDoc(File sourceFile, String controllerClass) {
BufferedReader reader = null;
boolean isJava = sourceFile.getName().endsWith(".java");
try {
reader = new BufferedReader(new FileReader(sourceFile));
String line;
String docDescription = "";
Map<String, String> params = new HashMap<>();
String controllerDescription = "";
while ((line = reader.readLine()) != null) {
if (line.matches(DOC_START)) {
docIndex = 0;
params = new HashMap<>();
hasDoc = true;
}
if (line.matches(DOC_END)) {
docIndex = -2;
}
if (docIndex == 1) {
docDescription = trimDocDescription(line);
}
if (line.matches(DOC_CLASS)) {
docIndex = -1;
if (hasDoc) {
controllerDescription = docDescription;
hasDoc = false;
}
}
if (line.matches(DOC_PARAMS)) {
String namedParam = getRexValue(DOC_PARAMS, line);
if (namedParam != null) {
String[] array = namedParam.split("\\s+");
if (array.length >= 2) {
params.put(array[0], substringArray(1, array));
}
}
}
scanControllerMethodDoc(
isJava,
controllerClass,
controllerDescription,
line, docDescription, params
);
if (docIndex != -2) docIndex++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 掃描方法注釋
*/
private void scanControllerMethodDoc(boolean isJava, String controllerName, String controllerDescription,
String line, String docDescription, Map<String, String> params) {
String regex = isJava ? DOC_METHOD_JAVA : DOC_METHOD_KT;
if (line.matches(regex)) {
String methodName = getRexValue(regex, line);
methodName = fixMethodName(methodName);
ApiDoc apiDoc = getApiDocBy(controllerName, methodName);
if (apiDoc != null) {
if (hasDoc) {
apiDoc.description = docDescription;
Utils.processRequestParam(params, controllerName, methodName);
apiDoc.params = params;
}
apiDoc.controllerDescription = controllerDescription;
}
if (hasDoc) hasDoc = false;
}
}
反射修改DocumentationCache
在我們掃描所有Controller源碼,獲取到注釋信息后,就可以修改DocumentationCache
了,不過要注意到是,DocumentationCache
中的相關屬性是private final
類型的,我們無法直接修改,需要通過反射的形式修改。
private void hookSwaggerDoc(Documentation doc) {
Multimap<String, ApiListing> apiList = doc.getApiListings();
for (ApiListing apiListing : apiList.values()) {
for (Model model : apiListing.getModels().values()) {
scanModelAndReplace(model);
}
for (ApiDescription apiDescription : apiListing.getApis()) {
String path = apiDescription.getPath();
ApiDoc apiDoc = docInfo.apiMap.get(path);
if (apiDoc != null) {
replaceParameter(apiDescription, apiDoc);
setOperationTags(apiDescription, apiDoc.controllerDescription);
setTags(apiListing.getTags(), apiDoc.controllerDescription, apiDoc.controllerClass);
}
}
}
}
線程啟動
要注意的是,DocumentationCache
最開始是沒有相關文檔信息的,我們在Spring Boot
項目啟動后再進行hook
文檔操作。這里我們可以通過多線程方式來完成。
public Swagger2Hook(DocumentationCache documentationCache, WebApplicationContext applicationContext) {
this.documentationCache = documentationCache;
this.applicationContext = applicationContext;
System.out.println("=======init easy swagger======");
new Thread() {
@Override
public void run() {
while (true) {
if (documentationCache.all().size() > 0) {
Swagger2Hook.this.run();
break;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
json保存文檔
因為我們是掃描源文件獲取文檔信息的,在部署時無法獲取。因此要將開發環境下的源碼信息保存到resources
目錄下的json文件中,然后通過讀取json文件而非掃描源碼形式來修改swagger文檔信息。
項目地址
https://github.com/iamyours/EasySwagger
https://search.maven.org/artifact/io.github.iamyours/easyswagger