Recommend a non-intrusive document generation tool that replaces swagger-SmartDoc

Today, the front and back ends are separated. In order to ensure the progress, the front and back ends are generally developed simultaneously, so the back end needs to give the interface documentation before writing the implementation.

After the author constantly seeks to optimize the document writing program, at least tried the following ways:

  1. Handwriting, if the code has not yet been written, this method can be used as a thinking process, but it is not convenient to change it later; if the code is written and then the document is written, it will naturally feel a bit repetitive work;
  2. Based on Swagger's annotations, although it can automatically generate documents, it is too intrusive and has been used;
  3. Based on Spring Doc, spring's built-in document function, I feel a little difficult to use, I have not tried

However, today this plug-in is what the author has always wanted to do. It is still the sentence: programmers should be lazy and never reinvent the wheel!

Introduction to smart-doc

Its Github address and documentation

Smart-doc is a java restful api document generation tool. Smart-doc subverts the traditional implementation method like swagger which uses annotation intrusion to generate documents. Smart-doc is based on the analysis of the interface source code to generate interface documents, completely zero annotation intrusion, you only need to write according to the java standard comments, smart-doc can help you generate a simple and clear markdown or a GitBook style Static html document. If you are tired of countless annotations and strong intrusion pollution of document tools such as swagger, please embrace smart-doc!

Let's try it out below, personally it feels very useful.

How to use smart-doc

The project structure is very simple, even the project can be tested without running, as follows:

project

Plug-in installation

Check out the latest version of its plugin: https://mvnrepository.com/artifact/com.github.shalousun/smart-doc-maven-plugin

Then join the maven plugin:

	<plugin>
		<groupId>com.github.shalousun</groupId>
		<artifactId>smart-doc-maven-plugin</artifactId>
		<version>1.0.4</version>
		<configuration>
			<!--指定生成文档的使用的配置文件,配置文件放在自己的项目中-->
			<configFile>./src/main/resources/smart-doc.json</configFile>
			<!--指定项目名称-->
			<projectName>测试DEMO</projectName>
			<!--smart-doc实现自动分析依赖树加载第三方依赖的源码,如果一些框架依赖库加载不到导致报错,这时请使用excludes排除掉-->
			<!--                    <excludes>-->
			<!--                        &lt;!&ndash;格式为:groupId:artifactId;参考如下&ndash;&gt;-->
			<!--                        <exclude>com.alibaba:fastjson</exclude>-->
			<!--                    </excludes>-->
		</configuration>
		<executions>
			<execution>
				<!--如果不需要在执行编译时启动smart-doc,则将phase注释掉-->
				<phase>compile</phase>
				<goals>
					<goal>markdown</goal>
				</goals>
			</execution>
		</executions>
	</plugin>

Fill in the configuration

Which is the smart-doc.jsoncontent

{
  "outPath": "D:\\workspace\\demo\\smart-doc-demo\\doc",
  "allInOne": true,
  "customResponseFields": [
    {
      "name": "resultCode",
      "desc": "Response code",
      "value": "200"
    },
    {
      "name": "resultMsg",
      "desc": "错误信息",
      "value": null
    }
  ],
  "requestHeaders": [
    {
      "name": "token",
      "type": "string",
      "desc": "存放于cookie的校验信息",
      "required": true,
      "since": "-"
    }
  ]
}

customResponseFieldsThe return value entity of the corresponding controller here :

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ResponseResult<T> {

    /**
     * 状态码
     */
    private int resultCode;

    /**
     * 信息
     */
    private String resultMsg;

    /**
     * 时间戳
     */
    private Long tid;

    /**
     * 数据
     */
    private T data;
}

If you want to pass parameters in the header, you need to requestHeaders.

The complete configuration can refer to the document

Declare the interface and write a comment

First of all, what are the comments in Javadoc?

You can refer to: Java documentation notes

There are only a few that we often use to write interfaces:

  • @author
  • @param
  • @return
  • @since

Then discuss how to write beautiful documents, here is the official advice: https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

Here is a simple example:

import com.jimo.smartdocdemo.model.ResponseResult;
import com.jimo.smartdocdemo.model.User;
import org.springframework.web.bind.annotation.*;

/**
 * 用户API
 *
 * @author jimo
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    /**
     * 根据id获取用户
     *
     * @param id ID
     */
    @GetMapping("/{id}")
    public ResponseResult<User> getUser(@PathVariable Integer id) {
        return ResponseResult.create(new User(id, "U" + id, "pwd" + id));
    }
}	

User object to explain here under:
First field have a comment, just as explain the meaning of the parameters, while checking annotation support provided [JSR303].
For example, you can not empty field with the @NotNulllabel

import javax.validation.constraints.NotNull;

/**
 * 用户实体
 *
 * @author jimo
 * @version 1.0.0
 * @date 2020/3/25 20:22
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    /**
     * 主键id
     */
    private Integer id;
    /**
     * 用户名
     */
    @NotNull
    private String username;
    /**
     * 密码
     */
    @NotNull
    private String password;
}

Execute plugin to generate documentation

You can execute the maven command through the command line:

//生成html
mvn -Dfile.encoding=UTF-8 smart-doc:html
//生成markdown
mvn -Dfile.encoding=UTF-8 smart-doc:markdown
//生成adoc
mvn -Dfile.encoding=UTF-8 smart-doc:adoc
//生成postman json数据
mvn -Dfile.encoding=UTF-8 smart-doc:postman

You can also execute the plugin in IDEA:

Insert picture description here

effect

Insert picture description here
Insert picture description here

Need to emphasize the use

In practice, you will encounter 2 more common problems

  1. It is necessary to ignore some fields in the entity, the method given by smart-doc is to add @ignore: see documentation
    /**
     * 忽略,非參數
     *
     * @ignore
     */
    private String name;
  1. When annotating the method, you need to use a new annotation @apiNode, which represents the detailed content, so that the content of the anchor will not be much when generating html:
    /**
     * 获取特征(只是个简单的标题)
     *
     * @param param 参数
     * @apiNote 这是一段非常详细的描述
     */
	 @PostMapping("/feature")
    public ResponseResult<List<NameValue>> getFeature(){}
  1. Ignore the entire controller, there is no support yet, and an issue has been raised

to sum up

  1. Smart-doc is based on source code analysis to derive the interface structure, so it is zero intrusive;
  2. This kind of interface declaration is written first, and then the document is generated, which also fully meets the progress requirements. After all, it takes time to write the document, and it also reduces the modification. The true WYSIWYG;
  3. Allow programmers to develop the habit of writing comments, which must be written, comments are documents
  4. This process can be automated

Automate the process of publishing documents

  1. Generate documentation
  2. Pass the document to the server
    1. How to transfer to the server: manual, code upload (write a script)
  3. Render the document
    1. Direct rendering via nginx: you need to manually modify the nginx configuration to distinguish items by directory
    2. Through the back-end application rendering,
      you can develop custom functions
      to implement project creation, upload, and rendering together

nginx configuration

Here is a location configuration agent under nginx to proxy multiple static resources:

  1. We use a directory to store project documents, if there are multiple projects, distinguish by folder name:
# pwd
/deploy/doc
# ls
app1 app2
  1. Alias ​​for nginx configuration:
	location /deploy {
		alias /deploy/doc;
		index index.html;
		proxy_set_header X-Forwarded-Proto $scheme;
		error_page 404 /index.html;
	}
  1. Then visit the app1 document to visit: http: // host / deploy / app1
Published 80 original articles · Like 319 · Visits 340,000+

Guess you like

Origin blog.csdn.net/jimo_lonely/article/details/105125635