Introduction to the
Lkadoc is an open source interface document automatic generation tool, based on the SpringBoot platform, has very powerful interface document management functions. To solve the Java background developers to write interface documents, debugging interface. At the same time, it provides a simple, elegant, and rich UI interface to facilitate the interface interconnection between the back end and front end.
vision
We want to be the Java developer’s best gay friend, free ourselves from the pain of manual interface documentation, throw away the clunky Postman, double our productivity, stop working overtime, and spend more time with our families.
features
-
Non-intrusive: Its introduction has no impact on existing projects. Come quietly and silently.
-
Easy integration: a single startup annotation does all the configuration. Easy as a doornail.
-
Awesome annotation: one annotation can describe multiple parameters, multiple parameter structures, and even interface zero annotation. At the peak of heaven and earth.
-
Drag debugging: support online debugging interface, synchronous, asynchronous pressure test interface. Unmatched in the world.
-
Cool interface: the document interface is simple and elegant, which can meet the aesthetics of both front-end and back-end developers. The display of parameters can be switched between table and JSON format. It’s what you want. I want it.
-
Powerful support: support document aggregation, document download, object attribute grouping, display of new interface tags, dynamic modification of parameter status (highlighting, marking, description), global binding token, password verification and other powerful support functions. Icing on the cake, like a tiger with wings.
show
Automatically generated interface document UI page
Interface debugging page
Quick start
Create a SpringBoot project with IDEA called LkadocDemo and click Next
Select the Spring Web component and click Finish
Lkadoc dependencies were introduced in the pom.xml file of the LkadocDemo project (1.3.9 will be released on December 10, 2021, it may not be pulled down, it may be delayed for a few days, if not, you can use 1.3.8 first)
<! - Lkadoc package -- -- >
<dependency>
<groupId>com.github.liukaitydn</groupId>
<artifactId>lkadoc-api</artifactId>
<version>1.3.9</version>
</dependency>
Copy the code
Annotate @lkadocDemo on the LkadocDemoApplication project startup class
@LKADocument(basePackages="com.lkad.api")
@SpringBootApplication
public class LkadocDemoApplication {
public static void main(String[] args) { SpringApplication.run(LkadocDemoApplication.class, args); }}Copy the code
Prepare a user login registration module class -LKADemoController under the com.lkad. API package
@lkatype (value=" user login registration module ")
@RestController
@RequestMapping("user")
public class LKADemoController {
@ LKAMethod (value = "login")
@ LKAParam (names = {" name ", "PWD"}, values = {" user name ", "password"})
@ LKARespose (names = {" code ", "MSG"}, values = {" status code ", "message"})
@PostMapping("login")
public Map<String,Object> login(String name, String pwd) {
Map<String,Object> map = new HashMap<>();
map.put("code".200);
map.put("msg"."Login successful, welcome"+name+"Visit our system");
returnmap; }}Copy the code
Launch the project, open a browser, and enter the addresshttp://127.0.0.1:8080/lkadoc.html
If you can see the above interface, then congratulations to the guest officer, Lkadoc is working for you
Annotation is introduced
Lkadoc automatically generates interface documents based on annotations. Annotations are very powerful, and in order to use Lkadoc flexibly, you must have knowledge of annotations. Lkadoc makes compatibility processing for most of swagger annotations, just change the imported package path to com.lk.api.*.
@LKADocument
# @lkadocument is an annotation added to the SpringBoot startup class. It must be added otherwise the Lkadoc interface document will not be usable. It describes project information.
basePackages:Scan the packet paths of the interface. Multiple packets are separated by commas (,). Specifying the parent packet path can scan all the child packet paths under the parent packet [required].
# for example: basePackages = "com. The lkad. API, com. The lkad. Admin"
projectName:Project Name [Optional]
ProjectName ="Lkadoc test project"
description:Item Description optional
# example :description=" This project is designed to teach the use of Lkadoc"
serverNames:The address of the project to be aggregated, preceded by the name of the project (omitted) and followed by the address of the project (domain name can also be used), multiple separated by ",", used to aggregate the interface information of other projects, can be switched in the UI interface [Optional]
# example :serverNames=" Property project ^192.168.0.52:8081, rental system ^192.168.0.77:8001"
version:The version number of the project, with the version attribute annotated by @lkamethod to quickly locate the new interface [optional]
# for example: version = "1.0"
enabled:Interface document startup switch,true is enabled, false is disabled, default is enabled [Optional]
# for example: enabled = true
sconAll:Enable automatic recognition of unannotated description parameters. Default: false. [Optional]
# for example: sconAll = false
password:Set the password required to view interface documents. By default, no password is required. [Optional]
# for example: password = "123456"
classNum:Set maximum number of classes to be scanned. Default is 5000 classes to prevent memory overflow. [Optional]
# for example: classNum = "10000"
Copy the code
Note: @lkadocument annotation properties can also be configured in the application.properties file with lkad.basePackages=” X.X.X “, but @lkadocument can’t be omitted. If an Lkad attribute is configured in the application.properties file, then the @lkadocument annotation invalidates all the attributes, meaning you have to go either way
@LKAType
The following attributes are used to describe the class:
value:The role of classes [must]
Value =" test class"
description:Class description [Optional]
# example :description=" This class is just for testing"
hidden:Whether to hide information about this class in the UI. The default value is false. If true, all interfaces under this class will also be hidden.
# for example: hidden = false
order:Sort, the less the value, the more advanced. [Optional]
# for example: the order = 1
Copy the code
@LKAMethod
The following attributes are used to describe the interface:
value:The role of interfaces [must]
# example :value=" user login"
description:Description of the interface [Optional]
# example :description=" interface for APP login"
contentType:Request header ContentType, default application/ X-www-form-urlencoded [Optional]
# for example: contentType = "application/json"
author:Author [Optional]
# for example, the author = "l."
createTime:Interface creation time [Optional]
# for example: createTime = "2021-08-08"
updateTime:Interface modification time [Optional]
# for example: updateTime = "2021-10-01"
hidden:Whether to hide this interface in the UI. Default: false. [Optional]
# for example: hidden = false
version:Interface version number. If the project version number is the same, it will be marked as the new interface in the UI interface. [Optional]
# for example: version = "1.0"
download:This interface must be set to true if it involves downloading files. Default is false. [Optional]
# for example: download = false
token:Token authentication is required for the interface, which does not affect normal services. The default value is true. [Optional]
# for example: token = true
order:Sorting, the fewer the numbers, the more advanced [Optional]
# for example: the order = 1
directory:The parent directory must exist, otherwise it will not be displayed in the interface document. By default, the parent directory of the current class will not be displayed.
# example :directory=" user management"
Copy the code
@LKAParam / @LKAParams
# Specifies the information used to describe the request parameters. The s complex attribute indicates that multiple parameters can be set, but pay attention to the order of parameters. You can choose only one parameter with s or without S. It is recommended that you use the s complex attribute regardless of multiple parameters or single parameters. The s complex attribute is more flexible and intelligent. Common attributes:
name/names:Parameter name [required] (Required when setting the parameter name with name; Lkadoc can select the name of the parameter without adding the -- parameters parameter in the JDK version 1.8 or later. Lkadoc can select the name of the parameter without adding the -- parameters parameter.
# such as:
Name ="name"
Names ={"name"," PWD ","age"
# or,
#@LKAParams({
#@LKAParam(name="name",...) .
#@LKAParam(name="pwd",...) .
#@LKAParam(name="age",...)
#})
@lkaparams uses the same attribute as @lkaparams.
value/values:Parameter function [must]
# such as:
Value =" name"
Values ={" name "," password "," age "}
description/descriptions:Description of parameters [Optional]
# such as:
# single parameter configuration :description=" Name cannot exceed 5 Characters"
# Multiple parameter configuration: Descriptions ={" Name must not exceed 5 Characters "," password must not be less than 6 characters "," age between 18 and 60 "}
dataType/dataTypes:DataType [optional] (default value when configured with dataType: string.class; DataTypes of parameters that are automatically retrieved with dataTypes configuration; omit the configuration, but note the order of the parameters.)
# such as:
DataType = string.class // can be omitted here because the default is String
# multiple parameters configuration: dataTypes = {String class, the Date, class, Integer. The class} / / can be omitted if consistent and interface into the order automatically
required/requireds:Mandatory or not, default true [Optional] (It is easier to add "-n" after the name attribute value or "n~" before the value attribute value to indicate that the parameter is not mandatory)
# such as:
# Single parameter configuration: Required =false or name="name-n" or value="n~ user name"
#requireds={false,true,false}
# or names = {" name - n ", "PWD", "age - n}"
# or values={"n~ username "," password ","n~ age "}
paramType/paramTypes:The value can be query, header, or path. Optional. (When paramType is used, the default value is query. When configured with paramTypes, Lkadoc can automatically obtain parameter positions according to @pathVariable and @requestheader parameter annotations.
# such as:
# Single parameter configuration :paramType="query" // The default value is query
ParamTypes ={"query","header","path"} // If @pathVariable or @requestheader is added to the parameter, the position of the parameter can be automatically obtained
isArray/isArrays:Whether this parameter is a collection or array. Default is false. [Optional]
# such as:
# single parameter configuration :isArray=false
IsArrays ={false,true,false}
testData/testDatas:Test data [Optional] (It is easier to add test data after the "^" symbol after value)
# such as:
TestData =" testData "or value=" name ^ testData" // Select 1 from 2
TestDatas ={" testDatas ","123456","22"}
# or values = {" n ~ name ^ zhang SAN ", "password ^ 123456", "n ~ ^ age 22"} / / 2 choose 1 in one of two ways
type:Parameter object type [Optional] (Used when the interface request parameter is an object, but generally do not need to set, can be automatically identified)
Type = user.class //
group:Used with type to group object parameters and filter unnecessary parameters [Optional]
# example :group="add" //add is a group name previously configured on the User object's parameters
Copy the code
@LKAModel
The information used to describe the entity class
# Common attributes:
value:Function of attributes [Optional]
description:Attribute description [Optional]
Copy the code
@LKAProperty
The information used to describe attributes of an entity class is similar to the @lkaparam attribute
# Common attributes:
value:The role of attributes [must]
description:Attribute description [Optional]
hidden:Whether to hide this property in the UI. Default is false. [Optional]
testData:Test data [Optional] (It is easier to add test data after the "^" symbol after value)
required:Mandatory or not, default is true [Optional] (It is easier to use "n~" before value to indicate non-mandatory)
isArray:Whether it is an array or a collection, automatic recognition without setting [Optional]
type:If the attribute is an object type, you can use type to specify the attribute. This parameter is optional.
groups:[Optional] set group name to '-n' (' -n ')
Groups ={"add","update-n","info"}
Copy the code
@LKAGroup
# @lkagroup is an input parameter annotation that specifies which group of parameters to use as input parameters
Copy the code
@LKARespose/@LKAResposes
# describes the information used to describe the response parameters, similar to the @lkaparam attribute
# Common attributes
name/names:Parameter name or type [required]
value/values:Parameter function [must]
description/descriptions:Description of parameters [required]
dataType/dataTypes:Parameter dataTypes, automatically recognized when using dataTypes without setting [optional]
isArray/isArrays:Is it a collection or array? Default: false [Optional]
type:The name/names parameter can be automatically identified.
group:Used with type to group object parameters and filter unnecessary parameters [Optional]
Parameter # father
parentName:Parent parameter Name [Optional]
parentValue:Parent parameter effect [Optional]
parentDescription:Parent Parameter Description [Optional]
parentIsArray:Whether the parent argument is an array or a collection [Optional]
Parameter # ye
grandpaName:Name of ginseng [Optional]
grandpaValue:Effect of male ginseng [Optional]
grandpaDescription:Description of Ginseng [Optional]
grandpaIsArray:Whether the parameter is an array or a set [Optional]
Copy the code
The base application
In the basic application, I will use a large number of cases to demonstrate the methods and skills of using Lkadoc in various scenarios, so that people can quickly master the basic use of Lkadoc in cases. You can also appreciate the convenience and power of Lkadoc.
Simple request entry parameter example
Based on the Quick Start example, modify @lkadocument annotated below
// Add project name and project description
@lkadocument (basePackages="com.lkad.api",projectName =" demo project ", Description =" For Lkadoc teaching project ")
@SpringBootApplication
public class LkadocDemoApplication {
public static void main(String[] args) { SpringApplication.run(LkadocDemoApplication.class, args); }}Copy the code
Under the LKADemoController class we add another registered method
// Note :JDK8 and above @lkaparam annotated names={"name"," PWD ","email","age"} configuration can be omitted
@lkamethod (value=" user register ",description="APP register interface ",version="1.0",createTime="2021-08-08",author="LK")
@ LKAParam (names = {" name ", "PWD", "email", "age"}, values = {" username ^ made ", "password ^ 123 ABC", "n ~ email ^ 123 @qq.com", "n ~ ^ age 21"})
@PostMapping("reg")
public String reg(String name,String pwd,String email,Integer age) {
if(name == null || "".equals(name) || pwd == null || "".equals(pwd)){
return "Registration failed";
}
return "Registration successful";
}
Copy the code
Launch the project, open a browser, and enter the addresshttp://127.0.0.1:8080/lkadoc.html, the interface is as follows:
Example path and header request entry parameters
Lkadoc can automatically recognize @requestheader and @pathVariable annotations by adding a test method with path and header inputs
@lkamethod (value="path and header ")
@ LKAParam (names = {" token ", "name", "email"}, values = {token ^ "aaaa", "n ~ name ^ melon melon", "n ~ email ^ 123 @qq.com"})
@PostMapping("getUser/{name}/{email}")
public String getUser(@RequestHeader("token") String token,
@PathVariable("name") String name,
@PathVariable("email") String email) {
return "Test result: token="+token+",name="+name+",email="+email;
}
Copy the code
Restart the project and refresh the Lkadoc interface as follows:
Array request input parameter example
Add a test method for array input parameters
//isArrays = {true,false} means that the first argument is an array and the second argument is not an array
@lkamethod (value=" array entry ")
@ LKAParam (names = {" ids ", "name"}, values = {^ 1001 "user ID", "n ~ name ^ guagua"}, isArrays = {} true, false)
@PostMapping("array")
public String array(Integer[] ids,String name) {
return Test Result: IDS =+ Arrays.toString(ids)+",name="+name;
}
Copy the code
Restart the project and refresh the Lkadoc interface as follows:
Example of file upload request entry parameters
Add a file upload test method
// contentType. FORMDATA Constant is multipart/form-data
@lkamethod (value=" upload files in batches ",contentType= contentType.formdata)
@lkaparam (Names =" files",values=" Upload files", isArrays= true)
@PostMapping("fileUpload")
public String fileUpload(MultipartFile[] files) {
String fileNames = "";
if(files ! =null) {
for (MultipartFile f : files) {
if("".equals(fileNames)) {
fileNames = f.getOriginalFilename();
}else {
fileNames = fileNames + ","+f.getOriginalFilename(); }}}return "Upload successful, file name:"+fileNames;
}
Copy the code
Restart the project and refresh the Lkadoc interface as follows:
File Download Example
Add a test method for file download
// @lkamethod download=true indicates that this method is a file download method. To test this method, prepare a test.txt file on disk D. The business logic of file download is not explained here.
@lkamethod (value=" download ",download=true)
@PostMapping("fileDownload")
public void fileDownload(HttpServletResponse response) throws Exception {
String path = "D:\\test.txt";
File file = new File(path);
String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toUpperCase();
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition"."attachment; filename=" + new String(file.getName().getBytes()));
response.addHeader("Content-Length"."" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
}
Copy the code
Restart the project and refresh the Lkadoc interface as follows:
Example of a simple object request entry parameter
When we enter an object, if the object has an @lkamodel annotation and its attributes have an @LkaProperty annotation, then Lkadoc will automatically scan the object information without having to add additional annotations to the interface to describe the object parameters. This will greatly reduce the number of comments on the interface and make it simpler if we use objects to operate on incoming parameters.
Prepare a role object under the com.lkad.model package
@LKAModel
public class Role {
@lkaProperty (value = "role id^101")
private Integer id;
@lkaProperty (value = "n~ role ^ name ")
private String name;
public Integer getId(a) {returnid; }public void setId(Integer id) {this.id = id; }public String getName(a) {returnname; }public void setName(String name) { this.name = name; }}Copy the code
Add a simple test method for object requests
@lkamethod (" Basic object entry ")
@GetMapping("getRole")
public Role getRole(Role role) {
return role;
}
Copy the code
Restart the project and refresh the Lkadoc interface as follows:
Complex object request input parameter example
Add two more objects, address and User, to the com.lkad.model package. Add three more objects, including Role
@LKAModel
public class Address {
@ LKAProperty (value = "^ 1" address ID)
private Integer id;
@lkaProperty (value="n~ LKAProperty ")
private String info;
public Integer getId(a) { return id; }
public void setId(Integer id) { this.id = id; }
public String getInfo(a) { return info; }
public void setInfo(String info) { this.info = info; }}Copy the code
@LKAModel
public class User {
^ 1001 @ LKAProperty (value = "user ID")
private Integer id;
@lkaProperty (value="n~ @lkaProperty ")
private String name;
@lkaProperty (value="n~ age ^20",description=" range 0-120")
private String age;
@lkaProperty (value=" role object ")
private Role role;
@lkaProperty (value=" user likes ^ sports ")
private String[] likes;
@lkaProperty (value=" address ")
private List<Address> addresses;
public Integer getId(a) { return id; }
public void setId(Integer id) { this.id = id; }
public String getName(a) { return name; }
public void setName(String name) { this.name = name; }
public String getAge(a) { return age; }
public void setAge(String age) { this.age = age; }
public Role getRole(a) { return role; }
public void setRole(Role role) { this.role = role; }
public String[] getLikes() { return likes; }
public void setLikes(String[] likes) { this.likes = likes; }
public List<Address> getAddresses(a) { return addresses; }
public void setAddresses(List<Address> addresses) { this.addresses = addresses; }}Copy the code
Add a test method for complex object requests
/** 1@LKAMethodThe annotation's contentType property is set to "application/json" 2. If contentType="application/json", add it to the front of the received object parameter@RequestBodyNote 3. If contentType="application/json", then the interface request type cannot be GET */
@lkamethod (value=" complex object pass ",contentType= contentType.json)
@PostMapping("addUser")
public User addUser(@RequestBody User user) {
return user;
}
Copy the code
Restart the project and refresh the Lkadoc interface as follows:
By clicking the “tree display request parameters” button, you can intuitively display the complex input parameter structure
Example of grouping object parameters
We found it more convenient to receive request parameters with objects, but how do we filter object attributes? For example, if you have a query interface that uses only the name and age parameters of the User object and the info parameters of addresses object, you don’t need to display all object attributes to the Lkadoc interface for front-end friendliness. Instead, you can use object parameter grouping.
- Groups can be named using the groups attribute of the @lkaProperty annotation
- An attribute can belong to multiple groups. The group names must be unique and separated by commas (,)
- There is no restriction on the group name, as long as it is not a blank string
- If you use properties inside a nested object, set the same group name on both the nested object name and the corresponding property
- An incoming parameter object needs the @LKagroup annotation to specify which set of parameters to use as incoming parameters
The groups attribute of the @lkaProperty annotation can be used to implement parameter groups. Multiple groups can be separated by ",". The group name is "getUser-n". The "-n" indicates that this parameter is a non-mandatory parameter in the group data
@LKAModel
public class User {
^ 1001 @ LKAProperty (value = "user ID")
private Integer id;
@lkaProperty (value="n ",groups = {"getUser","getUser2"})
private String name;
@lkaProperty (value="n~ age ^20",description=" range 0-120",groups = {"getUser-n"})
private String age;
@lkaProperty (value=" role object ")
private Role role;
@lkaProperty (value=" user likes ^ sports ")
private String[] likes;
@lkaProperty (value=" info ",groups = {"getUser"})// Groups = {"getUser"} cannot be omitted
privateList<Address> addresses; . Get and set methods... }Copy the code
@LKAModel
public class Address {
@ LKAProperty (value = "^ 1" address ID)
private Integer id;
@lkaProperty (value="n ",groups= {"getUser-n"})
privateString info; . Get and set methods (omitted)....... }Copy the code
Added a test method for grouping object parameters
// Add an annotation @lkagroup ("getUser") to the entry object User to indicate that in Lkadoc only the group named getUser is displayed
@lkamethod (value=" object parameters group ",contentType= contentType.json)
@PostMapping("getUserArray")
public User getUserArray(@RequestBody @LKAGroup("getUser") User user) {
return user;
}
Copy the code
Restart the project and refresh the Lkadoc interface as follows:
Simple sample response parameters
Prepare a user business module class -LKADemoController2 under the com.lkad. API package, and prepare a simple test method for response out parameters
@lkatype (value=" user business module ")
@RestController
@RequestMapping("business")
public class LKADemoController2 {
@lkamethod (" Simple response out parameter ")
@ LKARespose (names = {" code ", "MSG", "data"}, values = {" status code ", "message", "data"})
@GetMapping("getInfo")
public Map<String,Object> getInfo(a) {
Map<String,Object> map = new HashMap<>();
map.put("code".200);
map.put("msg"."Information obtained successfully");
map.put("data"."Response data");
returnmap; }}Copy the code
Restart the project and refresh the Lkadoc interface as follows:
Object response parameter example
Add another test method under the LKADemoController2 class
Lkadoc automatically scans the outgoing object for both the incoming and outgoing parameters if it is an object with @lkamodel and @lkaProperty annotations
@lkamethod (value=" object callback ",contentType= contentType.json)
@PostMapping("getUser")
public User getUser(@RequestBody User user) {
return user;
}
Copy the code
Restart the project and refresh the Lkadoc page. The following output is displayed:
Example of complex Map structure response parameters
Add a test method for complex Map structure response parameters under the LKADemoController2 class
@lkamethod (value=" complex Map structure response parameters ")
@ LKAResposes ({@ LKARespose (names = {" code ", "MSG"}, values = {" status code ", "message"}). @lkarespose (name="total",value=" total records ",parentName="result",parentValue=" response data "), @lkarespose (type= user. class,parentName="users",parentIsArray=true,parentValue=" User object list ",grandpaName="result")})
@GetMapping("getMap")
public Map<String,Object> getMap(a) {
Map<String,Object> map = new HashMap<>();
map.put("code".200);
map.put("msg"."Operation successful!");
Map<String,Object> data = new HashMap<>();
data.put("total".10);
List<User> users = new ArrayList<>();
User user1 = new User();
user1.setName("Zhang");
User user2 = new User();
user2.setName("Bill");
users.add(user1);
users.add(user2);
data.put("users",users);
map.put("result",data);
return map;
}
Copy the code
Restart the project and refresh the Lkadoc page. The following output is displayed:
By clicking the “Tree display response parameters” button, you can intuitively display the complex structure of response parameters
More than 3 layers of nested structure response parameter usage examples
A @lkarespose annotation with parentXXX and grandPaXXX attributes can only describe level 1 to 3 nodes at one time. What if there are level 5 or 10 nodes? There are also solutions, very simple, but may be more annotations, such as {a:{b:{c:{d:1}}}}, we can do this: @ LKARespose (name = “a”, value = “level”), @ LKARespose (name = “b”, value = “secondary”, parentName = “a”), @ LKARespose (name = “c”, value = “3”, parentName = “b”), @ LKARespose (name = “d” value = “4”, parentName = “c”)
Add a test method with more than three layers of nested structure usage skills under the LKADemoController2 class
@lkamethod (value=" More than 3 levels of nested structure usage tips ")
@lkaresposes ({@lkarespose (name="a",value=" c "), @lkarespose (name="b",value=" c ",parentName="a"), @lkaresposes ({@lkarespose (name="a",value=" C "), @ LKARespose (name = "c," value = "3", parentName = "b"), @ LKARespose (name = "d", value = "4", parentName = "c")})
@GetMapping("getMoreMap")
public Map<String,Object> getMoreMap(a){
Map<String,Object> mapa= new HashMap<>();
Map<String,Object> mapb= new HashMap<>();
Map<String,Object> mapc= new HashMap<>();
Map<String,Object> mapd= new HashMap<>();
mapa.put("a",mapb);
mapb.put("b",mapc);
mapc.put("c",mapd);
mapd.put("d".1);
return mapa;
}
Copy the code
Restart the project and refresh the Lkadoc page. The following output is displayed:
JSON formatted display
Example of complex object structure response parameters
In real work development, we usually prepare a encapsulated response parameter object to unify the interface’s output parameters. Now let’s demonstrate that the above complex Map structure response parameter example is transformed into an object structure.
Prepare a response wrapper object
@LKAModel
public class ApiResult {
@lkaProperty (value=" status code ")
private String code;
@ LKAProperty (value = "message")
private String msg;
@lkaProperty (value=" response data ")
private Map<String,Object> result = new HashMap<>();
private ApiResult(a) {}
public static ApiResult success(a) {
ApiResult res = new ApiResult();
return res;
}
public ApiResult put(String key,Object value) {
this.result.put(key, value);
return this;
}
public String getCode(a) { return code; }
public void setCode(String code) { this.code = code; }
public String getMsg(a) { return msg; }
public void setMsg(String msg) { this.msg = msg; }
public Map<String, Object> getResult(a) { return result; }
public void setResult(Map<String, Object> result) { this.result = result; }}Copy the code
Add a test method for complex object structure response parameters under the LKADemoController2 class
/** This method is the same as the complex Map struct response parameter example above, except that one is a Map and the other is an ApiResut object. However, we found that this method does not use a comment in the response parameter description:@LKARespose(Names = {"code"," MSG "},values= {" status code"," message "}) This is because the ApiResult object has passed@LKAPropertyThe annotation describes the "code" and "MSG" attributes, which Lkadoc will automatically scan for@LKAModelAnnotated response object. And if@LKAResposeIf the parameters described in the annotation match the attributes in the object,@LKAResposeThe argument described in the annotation overrides the property */ in the object
@lkamethod (value=" complex object structure response parameters ")
@lkaresposes ({@lkarespose (name="total",value=" total records ",parentName="result",parentValue=" response data "), @lkarespose (type= user. class,parentName="users",parentIsArray=true,parentValue=" User object list ",grandpaName="result")})
@PostMapping("getObj")
public ApiResult getObj(a) {
List<User> users = new ArrayList<User>();
User user1 = new User();
user1.setName("Zhang");
User user2 = new User();
user2.setName("Bill");
users.add(user1);
users.add(user2);
return ApiResult.success().put("total".10).put("users",users);
}
Copy the code
Restart the project and refresh the Lkadoc interface. The response parameters are displayed as follows, which is the same as the response parameters in the complex Map structure example above:
By clicking the “Tree display response parameters” button, you can intuitively display the complex structure of response parameters
Response parameter object parameter group
The group attribute of the @lKarespose annotation can also be used to group response parameters in the same way as request parameters.
Add a response parameter object parameter grouping test method under the LKADemoController2 class
The group = "getUser" attribute is added to type= user. class to display only the data from the getUser group
@lkamethod (value=" Response parameter object parameter group ")
@lkaresposes ({@lkarespose (name="total",value=" total records ",parentName="result",parentValue=" response data "), @LKARespose(type=User.class,group = "getUser",parentName="users",parentIsArray=true, ParentValue =" user object list ",grandpaName="result")})
@PostMapping("getObj2")
public ApiResult getObj2(a) {
List<User> users = new ArrayList<User>();
User user1 = new User();
user1.setName("Zhang");
User user2 = new User();
user2.setName("Bill");
users.add(user1);
users.add(user2);
return ApiResult.success().put("total".10).put("users",users);
}
Copy the code
Restart the project and refresh the Lkadoc page. The following output is displayed:
Advanced features
Lkadoc provides a number of very useful features that you can add to the benefits of using Lkadoc tools. With these features, you can quickly debug the interface, quickly locate errors, and even test code does not have to write. Can also greatly improve the efficiency of the interface with the front end, it is called interface magic!
Debugging API functions
Lkadoc allows you to debug a single interface. Just prepare the test data for the request parameters and click the “Execute Interface” button to see the debug result information in the debug window.
Lkadoc can also determine whether the interface should be “synchronous” or “asynchronous” by selecting the execution mode. If you select “synchronous” tests, you can select the number of times of execution, and the time interval, so that you can simulate stress testing the interface. If you select “asynchronous” tests, you can select the number of times you run them so that you can simulate concurrent testing of the interface. All test results are printed in the debug window.
Global request header Token locking
When debugging interfaces that require token authorization, we need token-like parameters in the request header of each interface that requires authorization, which is very inconvenient for debugging. Therefore, Lkadoc provides a method that can lock multiple request header parameters for the global interface (multiple request header parameters are used as “; “). In this way, you do not need to set these authorization parameters on each interface that requires authorization.
At the same time, we can use the token attribute of @Lkamethod to control whether the current interface needs token verification. If token=true, Lkadoc will automatically bring the locked request header parameter to the background when debugging the interface.
Quickly locate new interfaces
You remember that when you configure a project with @lkadocument annotation you have a version attribute that sets the version number of the project, and then the @Lkamethod annotation also has a Version attribute that sets the version number of the interface. In practice, Often a project version upgrade does not mean that all interfaces need to be upgraded, and some new interfaces may be added. So how do we figure out which interface is new or recently modified? Simply set the version value of the @Lkamethod annotation for the new interface or the newly modified interface to the version value of the @Lkadocument annotation, and Lkadoc will mark the new interface with a star. The back end can quickly identify the new interfaces when interfacing with the front end colleagues
Modified @lkadocument annotation below. Added the version=”1.0″ attribute configuration
@lkadocument (basePackages="com.lkad.api",projectName =" demo project ", Description =" For Lkadoc teaching project ",version =" 1.0")
@SpringBootApplication
public class LkadocDemoApplication {
public static void main(String[] args) { SpringApplication.run(LkadocDemoApplication.class, args); }}Copy the code
The version number of this interface is the same as the version number of the project, indicating that this is a new interface. In addition, the user registration interface generally does not require token verification. Here we set token=false
// Note :JDK8 and above @lkaparam annotated names={"name"," PWD ","email","age"} configuration can be omitted
@lkamethod (value=" user register ",description="APP register interface ",version="1.0",createTime="2021-08-08",author="LK",token=false)
@ LKAParam (names = {" name ", "PWD", "email", "age"}, values = {" username ^ made ", "password ^ 123 ABC", "n ~ email ^ 123 @qq.com", "n ~ ^ age 21"})
@PostMapping("reg")
public String reg(String name,String pwd,String email,Integer age) {
if(name == null || "".equals(name) || pwd == null || "".equals(pwd)){
return "Registration failed";
}
return "Registration successful";
}
Copy the code
Restart the project and refresh the Lkadoc page as follows:
Automatic recognition of unannotated parameters
When @Lkadocument’s sconAll=true, it scans out all of the interface’s parameters. Some of the parameters that aren’t annotated with @LkaProperty and @Lkaparam don’t have any function descriptions. In this case, you can add the function description of the parameter dynamically through custom Function or modify the function description that has been set.
@lkadocument commented below. Added the property configuration sconAll=true
@lkadocument (basePackages="com.lkad.api",projectName =" demo project ", Description =" For Lkadoc teaching project ",version =" 1.0",sconAll = true)
@SpringBootApplication
public class LkadocDemoApplication {
public static void main(String[] args) { SpringApplication.run(LkadocDemoApplication.class, args); }}Copy the code
Add an entity class with attributes that are not annotated, but the @lkamodel annotation must be added
@LKAModel
public class Dept {
private Integer id;
private String name;
public Integer getId(a) { return id; }
public void setId(Integer id) { this.id = id; }
public String getName(a) { return name; }
public void setName(String name) { this.name = name; }}Copy the code
Two new test methods are added
SconAll @ LKAMethod (value = "test")
@RequestMapping("testSconAll")
public ApiResult testSconAll(Dept dept){
return ApiResult.success();
}
SconAll2 @ LKAMethod (value = "test")
@RequestMapping("testSconAll2")
public ApiResult testSconAll2(Integer age,String[] likes){
return ApiResult.success();
}
Copy the code
Restart the project and refresh the document page as follows:
We can see that the input parameters are recognized, and we can change the parameter description by right clicking on the parameter name, and can also set the highlighting and delete state
Project polymerization
When we use microservices or multiple projects, we can aggregate the interface document information of multiple projects into a UI by configuring the @lkadocument annotation with the serverNames property. The left side of the “^” symbol is the project name, the right side is the project address, or the domain name, so that we can freely switch the interface information between the current project and other configured projects in the Lkadoc interface.
@lkadocument annotated below, added serverNames property configuration
@lkadocument (basePackages="com.lkad.api",projectName =" demo project ", Description =" For Lkadoc teaching project ", Version = "1.0",sconAll = true,serverNames = "192.168.0.52:8081, 192.168.0.77:8001")
@SpringBootApplication
public class LkadocDemoApplication {
public static void main(String[] args) { SpringApplication.run(LkadocDemoApplication.class, args); }}Copy the code
Restart the project and refresh the document as follows:
Document Export function
Lkadoc also provides export capability. Lkadoc supports exporting PDF or MarkDown interface documents in standardized format, which is very powerful and can meet the requirements of most scenarios. (Currently, only the interface for exporting the local project is supported.) Before exporting the PDF document, check whether the simsun. TTC font exists in the system. Windows system font path: C: / Windows/fonts/simsun. TTC Linux system font path: / usr/share/fonts/win/simsun TTC MAC system font path: /System/Library/Fonts/simsun.ttc
PDF effect:
MarkDown effect:
Set view password for Lkadoc
@lkadocument comments like this: Added the attribute configuration for password
@LKADocument(basePackages="com.lkad.api",projectName = "演示项目",description = "用于Lkadoc教学项目",
version = "1.0",sconAll = true,serverNames = "物业项目^192.168.0.52:8081,租房项目^192.168.0.77:8001",password = "123")
@SpringBootApplication
public class LkadocDemoApplication {
public static void main(String[] args) { SpringApplication.run(LkadocDemoApplication.class, args); }}Copy the code
Restart the project and refresh the document so that you need to enter a password to enter the Lkadoc screen:
If the password is incorrect, enter the error message page:
Note: In addition to setting the password for the document, you can turn off the document functionality in a production environment by setting the Enabled property value to false, which is not demonstrated here.
Interface sorting function
Both @lkatype and LKAMethod prompt for an Order attribute that sets the sorting of directories and interfaces, with the lower the value, the higher the order.
Merge directories and switch interfaces between directories
When the @Lkatype annotation value of multiple classes is the same, Lkadoc manages them in a single directory, and can also specify its upper directory through the @Lkamethod directory attribute. To switch a directory, the value of directory must exist. I’m not going to do it here, but you can try it yourself.
At the end
Thank you for your use and support, I hope it can bring you convenience in the work! If you feel good, please recommend to your friends or colleagues. Commitment life free, free to provide technical support! If you encounter problems or have good suggestions in the process of using, please leave a message to me, thank you!
Project open source address: code cloud ->gitee.com/liuk168/lka…
If you learn it well, give it a star
Update log
Version 1.3.8 has been released with the following updates:
- Whether attributes are controlled when adding debugging interfaces
- Header Token Adds multiple parameter Settings. Use semicolons (;) between multiple parameters. Separated. There must be a one-to-one correspondence between the key and value
- Fixed an issue where overloaded methods were overwritten
- increase
@LKAParam
Annotation automatically identifies parameter types (previously only@LKAParams
Comment valid) - Optimized basic packet scanning,
@LKADocument
Annotation adds the classNum attribute to control the total number of classes scanned, default5000
a - Optimize part of the code to increase tool performance
Version 1.3.9 has been released with the following major updates:
- Fixed the abnormal automatic recognition of parameter generic type, optimization support automatic recognition of parameter generic structure up to 4 layers, more than 4 layers is meaningless, indicating that there is a problem with the program
- Optimized UI interface, more compact, intuitive
- Optimized part of business logic code to increase tool stability
- This version will be released on December 10, 2021, and there may be delays in pulling to the local location. If you can’t pull it down, please try again in a day or two. thank you