Skip to content
shalousun edited this page Nov 3, 2019 · 12 revisions

Smart-doc has been loved by many young Java web application developers since it was opened in China in August 2018. I am very grateful to the developers who dare to try to use Smart-doc to help them get their work done faster. It is also shared here with java web application developers around the world.

1.Introduce

Smart-doc is based on java development to solve the problem of difficult and difficult to write java web restful interface documents. It is to help java web developers to quickly generate a simple and clear way by simply writing the standard java standard comments during development. The interface documentation also allows developers to have a simple and beautiful code that is not contaminated by unnecessary code.

2.Features

2.1 JSR303 support

In many current web projects, we will use JSR303 directly to verify the legality of the parameters, including whether the parameters are mandatory parameters, etc. Smart-doc itself is to help developers write less useless things, integrate standard development specifications. To help quickly generate documentation. Therefore, smart-doc has supported the JRS303 verification specification since its inception. As long as you write on the field, add the JSR303 validation annotation or the hibernate-validate annotation. The smart-doc auto-fill parameter when outputting the request parameter document is required to be true. Look at the code snippet:

public class User {
   /**
    * user name
    */
    @NotEmpty
    @Length(max = 5)
    private String name;

   /**
    * alias
    * @since 2.0
    */
    private String alias;

   /**
    * birthday
    */
    @NotBlank(message = "birthday can't be null")
    @Pattern(regexp = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$", message = "Birth date format is incorrect.")
    private String birthday;

   /**
    * age
    */
    @Min(value = 0)
    private Integer age;

}

Request-example:

Parameter Type Description Required Since
name string user name true -
alias string alias false 2.0
birthday string birthday true -
age int age false -

2.2 Response field ignored

Smart-doc automatically parses fastjson and jackson's ignored field annotations correctly into the document. This is relatively simple and will not be described in detail.

2.3 json data response field alias identification

Smart-doc can parse the name attribute value of fastjson's JSONField annotation and the value of the value of the spring Jackson's original Jackson's JsonProperty annotation to automatically complete the alias output. I have seen the json field ignore, here is a brief introduction.

public class User {
   /**
    * user name
    */
    @NotEmpty
    @Length(max = 5)
    private String name;

   /**
    * alias
    * @since 2.0
    */
    private String alias;

   /**
    * birthday
    */
    @NotBlank(message = "birthday can't be null")
    @Pattern(regexp = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$", message = "Birth date format is incorrect.")
    private String birthday;

   /**
    * age
    */
    @Min(value = 0)
    private Integer age;
}


Response-fields:

Field Type Description Required Since
name string user name true -
alias string alias false 2.0
birthday string birthday true -
age int age false -

Response-example:

{
	"name":"James",
	"alias":"James Harden",
	"birthday":"1999-09-30",
	"age":"20"
}


2.4 Request parameters are ignored

Sometimes in development, we may use the object model of the database directly to receive parameters directly, but fields like createTime and updateTime do not want to be output to the request parameter interface document. For the return data, it is actually better to handle, smart-doc itself can identify the fastjson and jackson fields to ignore the comments to filter out. There is no good solution to this for request parameters. Many documentation tools add annotations. Smart-doc adds request tags to provide request parameter filtering by using frequency and following the principle of not introducing annotations. This annotation tag definition For ignore. Note: This feature will only be available in version 1.5.

public class User {

    /**
     * user name
     */
    private String userName;

    /**
     * gender
     * @required
     */
    private int gender;

    /**
     *  create time 
     *  @ignore
     */
    private Timestamp createTime;

}

In the Controller layer, the @RequestBody User user used as the parameter to receive, and the request parameter document output by smart-doc:

Parameter Type Description Required Since
userName string user name false -
gender int gender true -

2.5 Parameter automatic analog value generation

In order to minimize the time for developers and testers to create parameter values, smart-doc provides automatic parameter values ​​for common field types and common field naming rules. Let's look directly at the use case:

public class User {

    /**
     * user name
     */
    private String name;

    /**
     * name 
     */
    private int age;

    /**
     * id card
     */
    @JSONField(name = "id_card")
    private String idCard;

    /**
     * gender
     *
     */
    private int gender;

    /**
     * email
     */
    private String email;

    /**
     * telphone
     */
    private String phone;

    /**
     *  create time
     *  @ignore
     */
    private Timestamp createTime;
}


The following is the response data in the smart-doc custom generated document, which relies on the source code to derive the completion.

Response-fields:

Field Type Description Since
name string user name -
age int age -
id_card string id_card -
gender int gender -
email string email -
phone string phone
createTime String create time -

Response-example:

{
	"name":"James Harden",
	"age":59,
	"id_card":"350308197203301780",
	"gender":0,
	"email":"[email protected]",
	"phone":"17664304058",
	"createTime":"2018-10-23 00:20:19"
}

2.6 Adding a Document Change Record

Since version 1.6.1, smart-doc has added the record function of document change records, and the generated documents are more in line with the actual document interaction scenarios. This feature only takes effect when you choose to use the allInOne setting. The usage is as follows:

ApiConfig config = new ApiConfig();
config.setServerUrl("http://localhost:8080");
config.setAllInOne(true);
config.setOutPath("d:\\md2");
//If you do not specify SourceCodePaths, Smart-doc loads the code under this project src/main/java by default.
config.setSourceCodePaths(
    SourceCodePath.path().setDesc("external project source code").setPath("src/main/java")
);
 //Add a document change record, which is not required, and the document change record will only take effect when setAllInOne is set to true.
 //https://gitee.com/sunyurepository/ApplicationPower/issues/IPS4O
config.setRevisionLogs(
 RevisionLog.getLog().setRevisionTime("2018/12/15").setAuthor("chen").setRemarks("test").setStatus("Create").setVersion("V1.0"),
 RevisionLog.getLog().setRevisionTime("2018/12/16").setAuthor("chen2").setRemarks("test2").setStatus("Modify").setVersion("V2.0")
);


The change is recorded in the header of the document, and the markdown style is as follows

Version Time Status Author Remarks
V1.0 2018/12/15 create chen test
V2.0 2018/12/16 modify chen2 test2

3.Generate and display html documents in the Spring Boot project

Smart-doc supports direct generation of html static documents. It is recommended that the generated documents be placed in the directory of the project src/main/resources/static/doc . After deploying the service, go directly to http://localhost:8080/doc/api.html You can see a html document with a perfect bookmark like gitbook. The style of the document is simple and clear. The steps are as follows:

3.1 Generate html documents

Write a unit test that generates the document; the code is as follows:

    @Test
    public void testBuilderControllersApi() {
        ApiConfig config = new ApiConfig();
        config.setServerUrl("http://localhost:8080");
        //If the strict mode is set to true, Smart-doc forces that the public method in each interface in the code has a comment.
        config.setStrict(true);
        //Set the api document output path.
        config.setOutPath(DocGlobalConstants.HTML_DOC_OUT_PATH);
   
        long start = System.currentTimeMillis();
        //HtmlApiDocBuilder is used to generate html documents, ApiDocBuilder is used to generate markdown documents, and ApiDocBuilder is used to generate AsciiDoc documents.
        HtmlApiDocBuilder.builderControllersApi(config);
        long end = System.currentTimeMillis();
        DateTimeUtil.printRunTime(end, start);
    }

3.2 Modifying Service Configuration

If the Spring Boot service is configured with spring.resources.add-mappings=false , the server will not process the static resources, and the html static api file generated by smart-doc will not be accessible. In this case, you only need to change the configuration to true . Of course, this configuration is best placed in the configuration center, the real production server if you do not want to expose the interface document can be directly set to false close the document.

3.3 html static api display effect

Best Practices

First of all, the implementation idea of ​​smart-doc is from the source code, there are many difficulties in the source code analysis, so the specification of the interface code is very high. In the feedback of smart-doc open source for more than a year, the code specification is high and the problems encountered are relatively few. The following points use suggestions:

  • Try to use independent parameters to receive objects. Parameter receiving objects try to avoid using enumeration classes (including enumeration properties) and using inner classes.
  • Do not use enumeration classes and inner classes in the return object.