In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you how to write the example code of the Spring Boot project integration Knife4j interface document, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article. Let's take a look at it.
Knife4j is the equivalent of an upgraded version of swagger. For me, it is much easier to use than swagger.
1. Introduce dependency package com.github.xiaoymin knife4j-spring-boot-starter 2.0.92 into pom.xml and create Knife4j configuration file package com.yuyun.config;import io.swagger.annotations.ApiOperation;import io.swagger.models.auth.In;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo Import springfox.documentation.service.ApiKey;import springfox.documentation.service.Contact;import springfox.documentation.service.SecurityScheme;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;import java.util.ArrayList;import java.util.List / * * @ author hyh * / @ Configuration@EnableSwagger2WebMvcpublic class Knife4jConfiguration {@ Bean (value = "defaultApi2") public Docket defaultApi2 () {Docket docket = new Docket (DocumentationType.SWAGGER_2) / / whether Swagger .enable (true) / / group name .groupName ("version 1.0") is enabled. / / basic information used to create the API Display in the page of the document (custom displayed information) .apiInfo (apiInfo ()) / / set which interfaces are exposed to Swagger for display. Select () / scan all annotated api It is more flexible in this way. Apis (RequestHandlerSelectors.withMethodAnnotation (ApiOperation.class)) / / specify Controller scan package path / / .apis (RequestHandlerSelectors.basePackage ("com.yuyun.controller")) / / scan all / / .apis (RequestHandlerSelectors.any ()) .build () Return docket;} private ApiInfo apiInfo () {String name = "rain cloud"; String url = "https://www.xxx.com/"; String email =" 1873591403@qq.com "; Contact contact = new Contact (name, url, email) Return new ApiInfoBuilder () .title ("API interface document") .description ("API interface document description") .termsOfServiceUrl ("https://www.xx.com/") .contact (contact) .version (" 1.0.1 ") .build ();}}
Note: if there is an error Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
Because the SpringBoot version is high, the error can be resolved by lowering the version or adding the following to application.yml
Spring: mvc: pathmatch: matching-strategy: ant_path_matcher
After the project runs, access the ip+ port number + / doc.html, such as http://localhost:8110/doc.html. The effect is as shown in the picture
3. Use Knife4j annotations
(1) used in entity classes
@ ApiModel is placed on the response entity class to describe the class
@ ApiModelProperty describes the properties of the response class
/ * * Enterprise Information Table * * @ author * @ since 1.0.0 2021-12-17 * / @ Data@ApiModel (value = "Enterprise Information Table") @ TableName ("company") public class CompanyDTO implements Serializable {private static final long serialVersionUID = 1L; / * * Primary key * / @ ApiModelProperty (value = "Primary key") private Long id / * Enterprise name * / @ ApiModelProperty (value = "Enterprise name") private String companyName; / * introduction * / @ ApiModelProperty (value = "introduction") private String description;}
(2) use in Controller layer
@ RestController@RequestMapping ("company") @ Api (tags = "Enterprise Information Table") public class CompanyController {@ Autowired private CompanyService companyService @ GetMapping ("getList") @ ApiOperation ("obtaining data according to conditions") @ ApiImplicitParams ({@ ApiImplicitParam (name = "id", value = "id", paramType = "query", required = true, dataType = "String"), @ ApiImplicitParam (name = "name", value = "name", paramType = "query", required = true, dataType = "String")) public Result getList (@ ApiParam (name = "address") Value = "address", required = true) String address) {List companyList = companyService.list () Return new Result () .success (companyList);}
There are some other notes that need to be further understood.
4. Global parameters
In the actual project, permissions are added to the access interface, and each access is accompanied by a request header parameter token. The global parameter is to facilitate the passing of a fixed parameter. When a global parameter is added, all interfaces take it with it.
First kind
Add to the configuration file
Private List securitySchemes () {List apiKeyList = new ArrayList (); apiKeyList.add (new ApiKey ("Authorization", "Authorization", In.HEADER.toValue ()); return apiKeyList;}
Referenced within the defaultApi2 () method
.securitySchemes (securitySchemes ())
The contents of the final configuration file:
@ Configuration@EnableSwagger2WebMvcpublic class Knife4jConfiguration {@ Bean (value = "defaultApi2") public Docket defaultApi2 () {Docket docket = new Docket (DocumentationType.SWAGGER_2) / / whether Swagger .enable (true) / / groupname .groupName ("version 1.0") / / basic information used to create the API Display in the page of the document (custom displayed information) .apiInfo (apiInfo ()) / / set which interfaces are exposed to Swagger for display. Select () / scan all annotated api It is more flexible in this way. Apis (RequestHandlerSelectors.withMethodAnnotation (ApiOperation.class)) / / specify Controller scan package path / / .apis (RequestHandlerSelectors.basePackage ("com.yuyun.controller")) / / scan all / / .apis (RequestHandlerSelectors.any ()) .scan (PathSelectors.any () .build () / * set the safe mode Swagger can set up access to token * / .securityschemes (securitySchemes ()) .securityConformations (securityContexts ()) .pathMapping ("/") Return docket;} private ApiInfo apiInfo () {String name = "rain cloud"; String url = "https://www.xxx.com/"; String email =" 1873591403@qq.com "; Contact contact = new Contact (name, url, email) Return new ApiInfoBuilder () .title ("API interface document") .description ("API interface document description") .termsOfServiceUrl ("https://www.xx.com/") .contact (contact) .version (" 1.0.1 ") .build () } / * Security mode, which specifies that token passes * / private List securitySchemes () {List apiKeyList = new ArrayList () through the Authorization header request header; apiKeyList.add (new ApiKey ("Authorization", "Authorization", "header")); return apiKeyList } / * Security context * / private List securityContexts () {List securityContexts = new ArrayList (); securityContexts.add (SecurityContext.builder () .securityReferences (defaultAuth ()). Build ()); return securityContexts Default security reference * / private List defaultAuth () {AuthorizationScope authorizationScope = new AuthorizationScope ("global", "accessEverything"); AuthorizationScope [] authorizationScopes = new AuthorizationScope [1]; authorizationScopes [0] = authorizationScope; List securityReferences = new ArrayList (); securityReferences.add (new SecurityReference ("Authorization", authorizationScopes)); return securityReferences;}}
Effect: add an Authorize to the menu and add information to the parameter values
Refresh, and then open the interface, you will find that there is an extra request header.
The second kind
Manage → global parameter settings directly in the menu document, and then add parameters:
If you open the interface again, you will find that the request header parameter is added.
The above is how to write the example code of the Spring Boot project integration Knife4j interface document. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.