当前位置:网站首页>[swagger]-swagger learning
[swagger]-swagger learning
2022-07-05 01:22:00 【Pacifica_】
Swagger Study
See video link
Official document link
SpringBoot Integrate Swagger
1. Import dependence
<!--Swagger jar package -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--Swagger ui Interface jar package -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2. establish Swagger Configuration class
@EnableSwagger2 // Turn on Swagger2
@Configuration // Mark that this class is the configuration class of the project
public class Swagger2Config {
}
3. Visit the project swagger-ui.html
Namely ui Interface
You can see ui The interface can be roughly divided into four parts : Selection box ,api Information , The control layer requests interface information and project model Entity class information
To configure swagger
swagger The configuration of requires a Docket Class bean. and Docket Class has only one constructor :
public Docket(DocumentationType documentationType) {
this.apiInfo = ApiInfo.DEFAULT;
......
this.documentationType = documentationType;
}
DocumentationType There are three in the class static final Embellished DocumentationType Variable :
public class DocumentationType extends SimplePluginMetadata {
public static final DocumentationType SWAGGER_12 = new DocumentationType("swagger", "1.2");
public static final DocumentationType SWAGGER_2 = new DocumentationType("swagger", "2.0");
public static final DocumentationType SPRING_WEB = new DocumentationType("spring-web", "1.0");
...
}
therefore Docket The constructor of only needs to be passed in DocumentationType.SWAGGER_2 that will do . Constructed in this way Docket The latter attributes are all default , You can use one of these methods to configure properties
Such as apiInfo Methods can be configured api Information ;enable Method can specify whether to open Swagger;groupName Method can specify this docket The interface of api Group name ;tags Method can configure some tags , It can be used when describing the name or description information of the controller ( Follow up @Api annotation );forCodeGeneration Method can set the format of generics when encoding , The specific description in the document is as follows :
To configure api Information
Docket Medium apiInfo Methods can be configured api Information about . This method needs to pass in a ApiInfo Class object , This class includes the following information :
private final String version; // Project version No
private final String title; // Project title
private final String description; // Description of the project
private final String termsOfServiceUrl; // Terms of service url
private final String license; // certificate
private final String licenseUrl; // certificate url
private final Contact contact; // Contacts
private final List<VendorExtension> vendorExtensions; // Other extended information
ApiInfo Class only provides full parameter constructors and properties get There is no way set Method , So you can use full parameter constructors to construct ApiInfo Class object . In addition, you can use ApiInfoBuilder Class to construct ApiInfo, With the help of ApiInfoBuilder It can be set by a single method ApiInfo The properties of , Than calling directly ApiInfo The full parameter constructor of class is more flexible and concise , After setting the property, call build Method can return a ApiInfo object , This method is actually calling ApliInfo All parameter construction method of
Configure tags
adopt Docket Medium tags Method can set labels , The method receives one Tags object , In general use Tag(String name, String description) Construction method construction , Appoint tag The name of and the tag Information to describe . Whether or not the constructed tag is used on the class or method, it will be in ui Displayed on the interface
When using, you only need to add @Api annotation , And then put one of them tags Attribute is specified as a Tags Of name Property to bind this class to this tag
Of course, the request method can also be related to a tags Bind together , But in this way, there will be no hierarchical relationship between methods and classes, but a parallel relationship , Readability is reduced
Configure interface information
Interface scan
adopt Docket Of select Method will get the Docket Of ApiSelectorBuilder Class object , This object is used to configure api Interface information
adopt apis Method specifies how to scan the interface , The method accepts a generic type RequestHandler Interface type Predicate Interface parameters ,RequestHandlerSelectors There is a specific implementation of this in the class :basePackage Method can specify to scan the request interface under a package ;any Scan all interfaces ;none No scanning ;withClassAnnotation Scan the interface in the class with the specified annotation ;withMethodAnnotation Scan the interface on the method with the specified annotation
adopt paths You can specify which request paths to scan , Be similar to apis Method , This method calls PathSelectors Methods in the class as parameters :any Specify to scan all request paths ;none Do not scan any paths ;ant Method to receive a string path pattern ( Such as "/**"), Specify the path that the scan conforms to the specified mode ;regex Method to receive a regular expression , Specify the path that scans for regular expressions
After the interface scanning is specified , call build Method can get the original Docket@ApiIgnore
Used on classes or methods or parameters , Indicates that the annotated item is to be ignored
Add interface description information
@Api
Used on classes , Add the description information of all interfaces in the whole class ( Use tags attribute )@ApiOperation
Used in methods , Add method ( Request interface ) Description information of @ApiParam
Used in method parameters ( Request parameters ) front , Add the description information of the parameter and whether the parameter is necessary
To configure api grouping
A project can Set multiple Docket, Every Docket Configure your own group name , Interface api Information and other properties , Different Docket The interfaces of are different groups , stay ui The selection box of the interface can select different groups for display
Configure entity class information
As long as the return value of the control layer request interface exists in the entity class , It will be scanned to swagger in
stay On entity class annotations @ApiModel
You can add the description information of the entity class
stay On member variables in entity classes annotations @ApiModelProperty
You can add the description information of the field ( If the member variable is public Decorate directly so that , If it is private Decoration needs to be added get and set The method works )
Code example
swagger Configuration class
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName(" Here is GroupName")
.forCodeGeneration(true)
.tags(new Tag(" This is the name of the tag "," This is the information to be described corresponding to the tag "))
.tags(new Tag(" This tag was created but not used "," It will still show "))
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.www.testcontroller"))
//.paths(PathSelectors.ant("/test/*"))
.build();
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName(" This is the second one GroupName");
}
public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title(" Here is title")
.version(" Here is version")
.description(" Here is description")
.build();
}
}
controller
@Api(value = " It's kind of ",tags = {
" This is the name of the tag "})
@RestController
@RequestMapping("/test")
public class TestController {
@ApiOperation(value = " This is the interface description ")
@GetMapping("/testUser")
public List<String> test(List<String> result) {
return new ArrayList<String>();
}
}
ui Interface
summary
It should be closed when it is officially released swagger, For safety reasons , Avoid exposing interfaces , At the same time, save the resources needed for operation
swagger Configuration is required at the code level , Annotations etc. , It has certain code implantability
边栏推荐
- Database postragesql client authentication
- SAP ui5 application development tutorial 107 - trial version of SAP ui5 overflow toolbar container control introduction
- How to use words to describe breaking change in Spartacus UI of SAP e-commerce cloud
- FEG founder rox:smartdefi will be the benchmark of the entire decentralized financial market
- Database postragesql lock management
- Grabbing and sorting out external articles -- status bar [4]
- Database postragesq PAM authentication
- Global and Chinese markets of radiation linear accelerators 2022-2028: Research Report on technology, participants, trends, market size and share
- Pandora IOT development board learning (RT thread) - Experiment 4 buzzer + motor experiment [key external interrupt] (learning notes)
- [microprocessor] VHDL development of microprocessor based on FPGA
猜你喜欢
Take you ten days to easily complete the go micro service series (IX. link tracking)
SAP ui5 application development tutorial 106 - how to improve the readability of SAP ui5 application routing URL trial version
Nebula Importer 数据导入实践
【海浪建模3】三维随机真实海浪建模以及海浪发电机建模matlab仿真
微信小程序:全网独家小程序版本独立微信社群人脉
[development of large e-commerce projects] performance pressure test - Performance Monitoring - heap memory and garbage collection -39
Applet live + e-commerce, if you want to be a new retail e-commerce, use it!
[wave modeling 2] three dimensional wave modeling and wave generator modeling matlab simulation
Complex, complicated and numerous: illustration of seven types of code coupling
Wechat applet: Xingxiu UI v1.5 WordPress system information resources blog download applet wechat QQ dual end source code support WordPress secondary classification loading animation optimization
随机推荐
Playwright recording
Jcenter () cannot find Alibaba cloud proxy address
Hand drawn video website
Nebula importer data import practice
[wave modeling 1] theoretical analysis and MATLAB simulation of wave modeling
Yyds dry goods inventory [Gan Di's one week summary: the most complete and detailed in the whole network]; detailed explanation of MySQL index data structure and index optimization; remember collectio
Query for Boolean field as "not true" (e.g. either false or non-existent)
Hedhat firewall
Discrete mathematics: propositional symbolization of predicate logic
Call Huawei order service to verify the purchase token interface and return connection reset
【FPGA教程案例10】基于Verilog的复数乘法器设计与实现
[wave modeling 3] three dimensional random real wave modeling and wave generator modeling matlab simulation
Global and Chinese market of nutrient analyzer 2022-2028: Research Report on technology, participants, trends, market size and share
Game 280 of leetcode week
Global and Chinese market of optical densitometers 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese markets for industrial X-ray testing equipment 2022-2028: Research Report on technology, participants, trends, market size and share
Using openpyxl module to write the binary list into excel file
如果消费互联网比喻成「湖泊」的话,产业互联网则是广阔的「海洋」
Database postragesql client authentication
揭露测试外包公司,关于外包,你或许听到过这样的声音