Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of generating interface documents for java integrated development SpringBoot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the method of generating interface documents for java integrated development SpringBoot". In daily operation, I believe that many people have doubts about the method of generating interface documents for java integrated development SpringBoot. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is the method of generating interface documents for java integrated development SpringBoot?" Next, please follow the editor to study!

Why use Swagger?

As programmers, we hate two things most: 1. Other people don't write notes. two。 Write your own notes.

As interface developers, we also hate two things:

1. Others do not write interface documents, and the documents are not updated in time.

two。 You need to write your own interface documentation and update it in a timely manner.

It is believed that both front-end and back-end developers have been tortured by interface documentation more or less. The front end often complains that the interface documents given by the back end are not consistent with the actual situation. The back end also feels that it takes a lot of effort to write and maintain interface documents, and it is often too late to update them.

With the popularity of micro services such as Springboot and Springcloud, there are hundreds of interface calls for each project, so it is almost impossible to write interface documents manually and ensure that the documents are updated in real time, so we urgently need a tool, a tool that can help us automatically generate interface documents and update documents automatically. It is Swagger.

Swagger provides a new way to maintain API documents, with four major advantages:

Automatically generate documents: with only a small amount of annotations, Swagger can automatically generate API documents according to the code, which ensures the timeliness of the documents.

Cross-language, supporting more than 40 languages.

Swagger UI presents an interactive API document, and we can try to call API directly on the document page, eliminating the process of preparing complex call parameters.

You can also import document specifications into related tools (such as SoapUI) that will automatically create automated tests for us.

Now that we know what Swagger does, let's integrate it into our project.

Swagger integration

Integrating Swagger is simple, with only three simple steps.

Step 1: introduce the dependency package io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2 step 2: modify the configuration file

Application.properties join configuration

# it is used to control whether Swagger is enabled. The production environment remembers to turn off Swagger and set the value to falsespringfox.swagger2.enabled = true.

Add a swagger configuration class

@ Configuration@EnableSwagger2@ConditionalOnClass (Docket.class) public class SwaggerConfig {private static final String VERSION = "1.0"; @ Value ("${springfox.swagger2.enabled}") private Boolean swaggerEnabled @ Bean public Docket createRestApi () {return new Docket (DocumentationType.SWAGGER_2) .enable (swaggerEnabled) .groupName ("SwaggerDemo") .apiInfo (apiInfo ()) .select () .apis (RequestHandlerSelectors.withClassAnnotation (Api.class)) .build () } / * add summary information * / private ApiInfo apiInfo () {return new ApiInfoBuilder () .title ("interface document") .contact (new Contact ("Java Daily Log", "http://javadaily.cn"," "jianzh6@163.com") .description ("Swagger interface document") .version (VERSION) .build () }}

Here through .apis (RequestHandlerSelectors.withClassAnnotation (Api.class))

Ostensibly, classes annotated with @ Api automatically generate interface documentation.

The third step is to configure the API interface @ RestController@Api (tags = "parameter verification") @ Slf4j@Validatedpublic class ValidController {@ PostMapping ("/ valid/test1") @ ApiOperation ("RequestBody verification") public String test1 (@ Validated @ RequestBody ValidVO validVO) {log.info ("validEntity is {}", validVO); return "test1 valid success" } @ ApiOperation ("Form check") @ PostMapping (value = "/ valid/test2") public String test2 (@ Validated ValidVO validVO) {log.info ("validEntity is {}", validVO); return "test2 valid success";} @ ApiOperation ("single parameter check") @ PostMapping (value = "/ valid/test3") public String test3 (@ Email String email) {log.info ("email is {}", email) Return "email valid success";}}

The @ Api annotation needs to generate the interface document, and the @ ApiOperation annotation marks the interface name.

At the same time, we also add the corresponding comments to ValidVO.

@ Data@ApiModel (value = "parameter check class") public class ValidVO {@ ApiModelProperty ("ID") private String id; @ ApiModelProperty (value = "apply ID", example = "cloud") private String appId; @ NotEmpty (message = "level cannot be empty") @ ApiModelProperty (value = "level") private String level; @ ApiModelProperty (value = "age") private int age;.}

This is a parameter entity annotated by @ ApiModel, which is described by the @ ApiModelProperty annotation field.

Unable to infer base url

In three simple steps, our project integrates the Swagger interface document. Start the service quickly and visit http://localhost:8080/swagger-ui.html to experience it.

Okay, there's a little problem, but don't panic.

The reason for this problem is that we added the return value / response body of ResponseBodyAdvice unified processing, so that the return value to Swagger is also wrapped in a layer, and the UI page cannot be parsed. You can observe the json data returned by Swagger through http://localhost:8080/v2/api-docs?group=SwaggerDemo.

Now that we know the cause of the problem, it's easy to solve, we just need to convert only the interface of our own project in the ResponseBodyAdvice processing class.

@ RestControllerAdvice (basePackages = "com.jianzh6.blog") @ Slf4jpublic class ResponseAdvice implements ResponseBodyAdvice {...}

The scope of the uniform return value is limited by adding the basePackage attribute, so that the Swagger is not affected.

Restart the server to access the swagger interface address again, and you can see the interface documentation page.

For input string: ""

Swagger2.9.2 has a bug, that is, when our parameter entity has parameters of type int, the backend always prompts an exception when the Swagger API page is opened:

Java.lang.NumberFormatException: For input string: "" at java.base/java.lang.NumberFormatException.forInputString (NumberFormatException.java:65) at java.base/java.lang.Long.parseLong (Long.java:702) at java.base/java.lang.Long.valueOf (Long.java:1144)

There are two solutions:

Add the example attribute when you annotate fields of type int with @ ApiModelPorperty

@ ApiModelProperty (value = "age", example = "10") private int age

Remove swagger-models and swagger-annotations from the original swagger and introduce higher versions of annotations and models by yourself

Io.springfox springfox-swagger2 2.9.2 io.swagger swagger-annotations io.swagger swagger-models io.swagger swagger-annotations 1.5.22 io.swagger swagger-models 1.5.22

Although there are two minor problems in the process of integrating Swagger, after solving them, we can enjoy the convenience that Swagger brings to us.

Swagger beautification

Swagger native UI is a bit ugly, and we can optimize it with Swagger's enhancement tool knife4j.

Step 1: introduce the dependency package com.github.xiaoymin knife4j-spring-boot-starter 2.0.4

Since swagger-annotations and swagger-models dependencies are already included in knife4j, we can remove the two dependencies we added manually above.

Step 2: enable knife4j enhancement @ Configuration@EnableSwagger2@ConditionalOnClass (Docket.class) @ EnableKnife4jpublic class SwaggerConfig {...}

Through the above two steps, we have completed the beautification of Swagger, and the effect can be seen by visiting http://localhost:8080/doc.html through the browser.

Swagger parameter grouping

When you see the students here, you must think, is that it? Is that what the old bird does? It's no different from our novice.

Don't worry, let's see an effect first.

First of all, we define two interfaces, one new and one editor.

@ ApiOperation ("add") @ PostMapping (value = "/ valid/add") public String add (@ Validated (value = {ValidGroup.Crud.Create.class}) ValidVO validVO) {log.info ("validEntity is {}", validVO); return "test3 valid success";} @ ApiOperation ("Update") @ PostMapping (value = "/ valid/update") public String update (@ Validated (value = ValidGroup.Crud.Update.class) ValidVO validVO) {log.info ("validEntity is {}", validVO); return "test4 valid success";}

Notice that the same entity ValidVO is used to receive the front-end parameters, but the grouping in the parameter verification is used, and then we open the kife4j page to see how the interface documents of the two are different.

New:

Edit:

As you can see from the above, although the entities used to accept parameters are the same, the parameters shown to the front end are also different when the grouping is different. This is the grouping function of Swagger.

Of course, native Swagger does not support grouping, so we need to extend Swagger. I have uploaded the code to github, because of the large amount of code, it will not be shown here, you can check it yourself.

After introducing the extension class, you also need to inject the corresponding Bean into the Swagger configuration class SwaggerConfig.

@ Configuration@EnableSwagger2@ConditionalOnClass (Docket.class) @ EnableKnife4jpublic class SwaggerConfig {. @ Bean @ Order (SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1000) public GroupOperationModelsProviderPlugin groupOperationModelsProviderPlugin () {return new GroupOperationModelsProviderPlugin ();} @ Bean @ Order (SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1000) public GroupModelBuilderPlugin groupModelBuilderPlugin () {return new GroupModelBuilderPlugin () @ Bean @ Order (SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1000) public GroupModelPropertyBuilderPlugin groupModelPropertyBuilderPlugin () {return new GroupModelPropertyBuilderPlugin ();} @ Bean @ Order (SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1000) public GroupExpandedParameterBuilderPlugin groupExpandedParameterBuilderPlugin () {return new GroupExpandedParameterBuilderPlugin ();} @ Bean @ Order (SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1000) public GroupOperationBuilderPlugin groupOperationBuilderPlugin () {return new GroupOperationBuilderPlugin () } @ Bean @ Primary @ Order (SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1000) public GroupModelAttributeParameterExpander groupModelAttributeParameterExpander (FieldProvider fields, AccessorsProvider accessors, EnumTypeDeterminer enumTypeDeterminer) {return new GroupModelAttributeParameterExpander (fields, accessors, enumTypeDeterminer);}} grouping instructions 1. Configure the following annotation @ Null (groups = ValidGroup.Crud.Create.class) @ NotNull (groups = ValidGroup.Crud.Update.class,message = "Application ID cannot be empty") @ ApiModelProperty (value = "apply ID", example = "cloud") private String appId in the properties of the bean object

When adding a scene, appId is empty and there is no need to pass a value; when modifying the scene, appId cannot be empty and needs to be passed; other groups that are not configured are default groups (Default)

two。 Add group rule verification @ ApiOperation ("add") @ PostMapping (value = "/ valid/add") public String add (@ Validated (value = {ValidGroup.Crud.Create.class}) ValidVO validVO) {log.info ("validEntity is {}", validVO) to the API parameter; return "test3 valid success";}

The current API verifies the bean attribute of the default group and the common attributes saved.

At this point, the study on "what is the method of generating interface documents for SpringBoot in java integrated development" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report