In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you about how to integrate Swagger3 and SpringBoot and generate offline documents. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.
Preface
With the evolution of project architecture, front and rear separation is an irresistible trend. One of the problems often encountered in the process of practice in this mode of collaboration is documentation.
Now that there is a pain point, there must be a product to address it, and this is Swagger, which has been updated to the Swagger3 version. If you are still stuck in Swagger2, it is recommended to upgrade to Swagger3, the overall UI style and interaction is much more friendly.
Introduction to Swagger
Swagger is a specification and complete framework for generating, describing, invoking, and visualizing RESTful-style Web services. The overall goal is to have the client and the file system update at the same speed as the server. The file's methods, parameters, and models are tightly integrated into the server-side code, allowing API to always keep synchronized.
Official website: https://swagger.io
Pain points solved by Swagger
The traditional way to provide documentation has the following pain points:
There are many interfaces, complex implementation details, laborious documentation and continuous maintenance.
Interface documents need to be synchronized at any time
The result returned by the interface is not clear, so you have to construct the return structure, etc.
The interface cannot be tested directly online, and additional tools, such as PostMan, are usually required.
With the introduction of Swagger, the above pain points can be easily solved, with the following advantages:
Timeliness (after the interface is changed, the front and back end can see the latest version in real time)
Normative (interface specific uniform style, such as interface address, request method, parameters, response format and error messages, etc.)
Consistency (the interface information is consistent, and there will be no differences due to the version of the interface document)
Testability (can be tested directly based on interface documentation)
Changes in Swagger3
The changes to Swagger3.0 are summarized in the official document as follows:
Removed dependency on springfox-swagger2
Delete all @ EnableSwagger2... Notes
Added springfox-boot-starter dependency
Removed third-party dependencies such as guava
The document access address is changed to http://ip:port/project/swagger-ui/index.html.
Next, let's use it in practice.
SpringBoot integrated Swagger3
SpringBoot integration Swagger3 is basically the same as SpringBoot integration with other frameworks, which usually include introducing dependencies, specifying configuration files, creating configuration classes, and using.
Introduce dependency
Introduce Swagger3 dependencies into the pom.xml of the SpringBoot project:
Io.springfox springfox-boot-starter 3.0.0
Specify profile
In general, swagger can only be opened in the development environment or test environment, and needs to be closed in the production environment. The enabling and closing of swagger can be configured in application.properties:
# production environment needs to be set to false springfox.documentation.swagger-ui.enabled=true
Configuration class
Start the use of Swagger with the @ EnableOpenApi annotation, and configure the common parameters of Swagger in the configuration class.
@ Configuration @ EnableOpenApi public class Swagger3Config {@ Bean public Docket createRestApi () {/ / returns document summary information return new Docket (DocumentationType.OAS_30) .apiInfo (apiInfo ()) .select () .apis (RequestHandlerSelectors.withMethodAnnotation (Operation.class)) .documentation (PathSelectors.any ()) .build () .globalRequestParameters (getGlobalRequestParameters ()) .globalResponses (HttpMethod.GET GetGlobalResponseMessage () .globalResponses (HttpMethod.POST, getGlobalResponseMessage ()) } / * generate interface information, including title, contact, etc. * / private ApiInfo apiInfo () {return new ApiInfoBuilder () .title ("Swagger3 interface document") .description ("if in doubt, please contact the second brother. Wechat: zhuan2quan ") .contact (new Contact (" second brother "," https://www.choupangxia.com/", "secbro2@gmail.com")) .version ("1.0") .build () } / * encapsulate the global common parameter * / private List getGlobalRequestParameters () {List parameters = new ArrayList () Parameters.add (new RequestParameterBuilder () .name ("uuid") .description ("device uuid") .required (true) .in (ParameterType.QUERY) .query (Q-> q.model (m-> m.scalarModel (ScalarType.STRING) .required ( False) .build () Return parameters;} / * encapsulates general response information * / private List getGlobalResponseMessage () {List responseList = new ArrayList (); responseList.add (new ResponseBuilder (). Code ("404"). Description ("Resource not found"). Build (); return responseList;}}
The integration of Spring Boot and Swagger has been completed through the above configuration, so let's show how to use it in the business logic.
Used in business
Create two entity classes, Goods (commodity class) and CommonResult (generic return result class).
Goods class:
@ ApiModel ("commodity model") public class Goods {/ * Commodity id * / @ ApiModelProperty ("Commodity ID") Long goodsId; / * Commodity name * / @ ApiModelProperty ("Commodity name") private String goodsName; / * Commodity Price * / @ ApiModelProperty ("Commodity Price") private BigDecimal price / / omit getter/setter}
CommonResult class:
@ ApiModel ("API common data") public class CommonResult {/ * identification code. 0 means success, non-0 means error * / @ ApiModelProperty ("identification code, 0 means success, non-0 means error") private Integer code; / * * description information, usually use * / @ ApiModelProperty ("error description") private String msg in case of error. / * Business data * / @ ApiModelProperty ("Business data") private T data; public CommonResult (Integer status, String msg, T data) {this.code = status; this.msg = msg; this.data = data } / * * successful * / public static CommonResult success (T data) {return new CommonResult (0, "success", data);} public static CommonResult success (Integer code, String msg) {return new CommonResult (code, msg, null) } / * error * / public static CommonResult error (int code, String msg) {return new CommonResult (code, msg, null);} / / omit getter/setter}
Let's use the API corresponding to Swagger for the interface of the Controller layer.
GoodsController class:
@ Api (tags = "Commodity Information Management Interface") @ RestController @ RequestMapping ("/ goods") public class GoodsController {@ Operation (summary = "individual commodity details") @ GetMapping ("/ findGoodsById") public CommonResult findGoodsById (@ Parameter (description = "commodity ID, positive integer") @ RequestParam (value = "goodsId", required = false DefaultValue = "0") Integer goodsId) {System.out.println ("according to commodity ID=" + goodsId + "query commodity details") Goods goods = new Goods (); goods.setGoodsId (1L); goods.setGoodsName (Notebook); goods.setPrice (new BigDecimal (8888)); return CommonResult.success (goods);}}
OrderController class:
@ Api (tags = "order Management Interface") @ RestController @ RequestMapping ("/ order") public class OrderController {@ Operation (summary = "submit order") @ PostMapping ("/ order") @ ApiImplicitParams ({@ ApiImplicitParam (name = "userId", value = "user id", dataTypeClass = Long.class, paramType = "query", example = "123"), @ ApiImplicitParam (name = "goodsId", value = "Commodity id") DataTypeClass = Integer.class, paramType = "query", example = "1")}) public CommonResult toBuy (@ ApiIgnore @ RequestParam Map params) {System.out.println (params) Return CommonResult.success ("success");}}
Display effect
Complete the integration and start the SpringBoot project at the access address:
Http://127.0.0.1:8080/swagger-ui/index.html
As a whole, you can see the following effect:
For the specific commodity information management API, you can see the request parameters, return result data structure and other information. Click "Try it out" to enter the parameter request parameters to call the API:
The corresponding processing result is returned after the call:
You can also see the corresponding returned result data and entity class information annotated by Swagger in the bottom Schemas.
Instructions for the use of Swagger3 comments
After the above examples, we know how most API is used, so let's summarize the functions of the relevant API:
@ Api: used on the requested class, indicating the description of the class tags= "indicates the function of the class. The note" value= "that can be seen on the UI interface does not make any sense, and it can also be seen on the UI interface, so there is no need to configure" @ ApiOperation: used on the requested method. " Description of the purpose of the method, function of value= "description of the use of the method, notes for the" notes= "method @ ApiImplicitParams: used on the requested method, indicating a set of parameter descriptions @ ApiImplicitParam: used in @ ApiImplicitParams comments Specify all aspects of a request parameter name: parameter name value: the Chinese character description of the parameter, Explain whether the required: parameter must pass paramType: where to put the parameter header-- > request parameter acquisition: @ RequestHeader query-- > request parameter acquisition: @ RequestParam path (for restful API)-> request parameter acquisition: @ PathVariable body (not commonly used) Form (rarely used) dataType: parameter type Default String, other values dataType= "Integer" defaultValue: default value @ ApiResponses: used in the request method to represent a set of responses @ ApiResponse: used in @ ApiResponses, it is generally used to express an error response information code: number, such as 400 message: information, such as "request parameters are not filled" response: class @ ApiModel: used on the response class Represents a message that returns response data (this is commonly used in scenarios such as @ RequestBody when post is created, where request parameters cannot be described using @ ApiImplicitParam annotations) @ ApiModelProperty: used on attributes to describe the properties of the response class, integrating knife4j to export offline documents
Swagger provides us with convenient online documentation support, but in some scenarios we need to provide interface documentation to partners rather than directly to an address. At this point, we need to export the interface document as an offline document.
Here we integrate enhanced document knife4j to export offline documents.
Add knife4j dependency
Add knife4j dependencies to pom.xml:
Com.github.xiaoymin knife4j-spring-boot-starter 3.0.2
Start knife4j
Add the @ EnableKnife4j annotation to the Swagger3Config configured for Swagger above, which turns on the enhancements to knife4j.
EnableKnife4j @ Configuration @ EnableOpenApi public class Swagger3Config {/ /...}
At this point, if you still visit http://localhost:8080/swagger-ui/index.html, you will find that the display has not changed. Here we need to visit http://localhost:8088/doc.html.
The whole project source address: https://github.com/secbr/springboot-all/tree/master/springboot-swagger3.
Display effect
After starting the project and visiting doc.html, you will find that the document style has become very cool now. Show a few effects to take a look:
In the "offline documents" column, you can see four forms of offline document downloads: Markdown, HTML, Word, and OpenAPI.
Among them, I feel that the document in HTML format is more bold and easier to view, so let's take a picture to see the effect.
Summary
Documentation is a must in the project, but with the development of open source frameworks, the pain points of documentation for technicians are gradually being resolved. If you are still in the stage of handwritten documents, you can really try this kind of more friendly document presentation.
The above is the editor to share with you how to integrate Swagger3 and SpringBoot and generate offline documents. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to 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.