Follow the crazy god SpringBoot project to integrate Swagger

Follow the crazy god SpringBoot project to integrate Swagger

Project integration Swagger

Insert picture description here

learning target:

  • Understand the concept and function of Swagger

  • Master the integration of Swagger in the project to automatically generate API documentation

Introduction to Swagger

Front and rear separation

  • Front end -> Front end control layer, view layer

  • Back-end -> Back-end control layer, service layer, data access layer

  • Front-end and back-end interact through API

  • The front and rear ends are relatively independent and loosely coupled

The problem

  • Front-end and back-end integration, the front-end or back-end cannot be "negotiated in time and resolved as soon as possible", resulting in a concentrated outbreak of problems

solution

  • First define schema[the outline of the plan], and track the latest API in real time to reduce integration risks

Swagger

  • Known as the most popular API framework in the world

  • Restful Api document online automatic generator => API document and API definition are updated synchronously

  • Run directly, test the API online

  • Support multiple languages ​​(such as: Java, PHP, etc.)

  • Official website: https://swagger.io/

SpringBoot integrates Swagger

SpringBoot integrates Swagger => springfox , two jar packages

  • Springfox-swagger2

  • swagger-springmvc

Use Swagger

Requirements: jdk 1.8 + otherwise swagger2 cannot run

step:

1. Create a new SpringBoot-webproject

2. Add Maven dependency

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.2</version>
</dependency>

3. Write HelloControllerand test to ensure successful operation!

4. To use Swagger, we need to write a configuration class- SwaggerConfigto configureSwagger

@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
public class SwaggerConfig {
    
      
}

5. Access test:, the interface http://localhost:8080/swagger-ui.htmlthat can be seen swagger;

Insert picture description here

Configure Swagger

1. The Swaggerinstance Beanis Docket, so it is configured by configuring the Docketinstance Swaggger.

SwaggerConfig

@Bean //配置docket以配置Swagger具体参数
public Docket docket() {
    
    
   return new Docket(DocumentationType.SWAGGER_2);
}

2. apiInfo()Document information can be configured through properties

//配置文档信息
private ApiInfo apiInfo() {
    
    
   Contact contact = new Contact("联系人名字", "http://xxx.xxx.com/联系人访问链接", "联系人邮箱");
   return new ApiInfo(
           "Swagger学习", // 标题
           "学习演示如何配置Swagger", // 描述
           "v1.0", // 版本
           "http://terms.service.url/组织链接", // 组织链接
           contact, // 联系人信息
           "Apach 2.0 许可", // 许可
           "许可链接", // 许可连接
           new ArrayList<>()// 扩展
  );
}

3. DocketInstance associationapiInfo()

@Bean
public Docket docket() {
    
    
   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}

4, restart the project, access the test http://localhost:8080/swagger-ui.htmlfacie effect;

Configure scan interface

1. Configure how to scan the interface Docketthrough the select()method during construction .

@Bean
public Docket docket() {
    
    
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
      .build();
}

2. Restart the project test. Since we configured to scan the interface according to the path of the package, we can only see one class

3. In addition to configuring the scanning interface through the packet path, you can also configure other methods to scan the interface. Here are all the configuration methods:

any() // 扫描所有,项目中的所有接口都会被扫描到
none() // 不扫描接口
// 通过方法上的注解扫描,如withMethodAnnotation(GetMapping.class)只扫描get请求
withMethodAnnotation(final Class<? extends Annotation> annotation)
// 通过类上的注解扫描,如.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口
withClassAnnotation(final Class<? extends Annotation> annotation)
basePackage(final String basePackage) // 根据包路径扫描接口

4. In addition, we can also configure interface scan filtering:

@Bean
public Docket docket() {
    
    
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}

5. The optional values ​​here are

any() // 任何请求都扫描
none() // 任何请求都不扫描
regex(final String pathRegex) // 通过正则表达式控制
ant(final String antPattern) // 通过ant()控制

Insert picture description here

Configure Swagger switch

1. Use the enable()method to configure whether to enable or not swagger, if it is false, it swaggerwill not be accessible in the browser

@Bean
public Docket docket() {
    
    
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(false) //配置是否启用Swagger,如果是false,在浏览器将无法访问
      .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}

2, when the project is how dynamic configuration test, devthe display environment swagger, in prodnot displayed?

@Bean
public Docket docket(Environment environment) {
    
    
   // 设置要显示swagger的环境
   Profiles of = Profiles.of("dev", "test");
   // 判断当前是否处于该环境
   // 通过 enable() 接收此参数判断是否要显示
   boolean b = environment.acceptsProfiles(of);
   
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(b) //配置是否启用Swagger,如果是false,在浏览器将无法访问
      .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}

Configuration Environment
application.properties

spring.profiles.active=dev

application-dev.properties

server.port=8080

application-test.properties

server.port=8080

3. You can add a dev configuration file to the project to check the effect!

Insert picture description here

Configure API grouping

1. If the grouping is not configured, the default is default. The groupName()grouping can be configured by the method:

@Bean
public Docket docket(Environment environment) {
    
    
   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
      .groupName("hello") // 配置分组
       // 省略配置....
}

2. Restart the project to view the group

3. How to configure multiple groups? To configure multiple groups, you only need to configure multiple groups docket:

@Bean
public Docket docket1(){
    
    
   return new Docket(DocumentationType.SWAGGER_2).groupName("group1");
}
@Bean
public Docket docket2(){
    
    
   return new Docket(DocumentationType.SWAGGER_2).groupName("group2");
}
@Bean
public Docket docket3(){
    
    
   return new Docket(DocumentationType.SWAGGER_2).groupName("group3");
}

4. Restart the project to view

Entity configuration

1. Create a new entity class

@ApiModel("用户实体")
public class User {
    
    
   @ApiModelProperty("用户名")
   public String username;
   @ApiModelProperty("密码")
   public String password;
}

2. As long as this entity is in the return value of the request interface (even if it is a generic), it can be mapped to the entity item:

@RequestMapping("/getUser")
public User getUser(){
    
    
   return new User();
}

3. Restart to view the test

Insert picture description here

Note: It is not because @ApiModelthis annotation makes the entity appear here, but as long as the entity appears on the return value of the interface method, it will be displayed here, @ApiModeland @ApiModelPropertythese two annotations are just for adding annotations to the entity.

@ApiModelAnnotate the class

@ApiModelPropertyAdd annotations to class attributes

Common notes

SwaggerAll annotations are defined under the io.swagger.annotationspackage

Some frequently used ones are listed below. For those not listed, please refer to the explanation separately:

Swagger annotation Brief description
@Api(tags = "xxx模块说明") Act on the module class
@ApiOperation("xxx接口说明") Act on interface methods
@ApiModel("xxxPOJO说明") Act on the model class: such as VO, BO
@ApiModelProperty(value = "xxx属性说明",hidden = true) Act on class methods and properties, hidden is set to true to hide the property
@ApiParam("xxx参数说明") Act on parameters, methods and fields, similar@ApiModelProperty

We can also configure some annotations for the requested interface

@ApiOperation("狂神的接口")
@PostMapping("/kuang")
@ResponseBody
public String kuang(@ApiParam("这个名字会被返回")String username){
    
    
   return username;
}

In this way, you can add some configuration information to some more difficult to understand attributes or interfaces, so that it is easier to read!

Compared with the traditional Postmanor Curlmethod test interface, using it is swaggersimply a foolish operation. It does not require additional documentation (well written is a document in itself) and is less error-prone. Just enter the data and click Execute. If you cooperate with the automation framework, It can be said that human operation is basically unnecessary.

SwaggerIt is an excellent tool. Now many small and medium-sized Internet companies in China are using it. Compared with the traditional method of exporting Wordinterface documents and then testing, it is obviously more in line with the current rapid iterative development market. Of course, I remind everyone to remember to close it in the formal environment Swagger. First, for safety reasons, it can also save runtime memory.

Test the swagger controller

HelloControllerwrite

    @ApiOperation(value = "/hello3", notes = "测试hello3")
    @ApiImplicitParams({
    
    
            @ApiImplicitParam(paramType = "query", name = "str", value = "str", dataType = "string")
            , @ApiImplicitParam(paramType = "query", name = "age", value = "12", dataType = "Integer")})
    @GetMapping(value = "/hello3")
    public String hello3(String str, Integer age) {
    
    
        String s = str + ":" + age;
        return s;
    }

Insert picture description here
Insert picture description here
Insert picture description here

Expansion: other skins

We can import different packages to achieve different skin definitions:

1. The default access http://localhost:8080/swagger-ui.html

<dependency> 
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.2</version>
</dependency>

Insert picture description here

2. bootstrap-uiVisithttp://localhost:8080/doc.html

<!-- 引入swagger-bootstrap-ui包 /doc.html-->
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>swagger-bootstrap-ui</artifactId>
   <version>1.9.1</version>
</dependency>

Insert picture description here

3. Layui-uiVisithttp://localhost:8080/docs.html

<!-- 引入swagger-ui-layer包 /docs.html-->
<dependency>
   <groupId>com.github.caspar-chen</groupId>
   <artifactId>swagger-ui-layer</artifactId>
   <version>1.1.3</version>
</dependency>

4. mg-uiVisithttp://localhost:8080/document.html

<!-- 引入swagger-ui-layer包 /document.html-->
<dependency>
   <groupId>com.zyplayer</groupId>
   <artifactId>swagger-mg-ui</artifactId>
   <version>1.0.6</version>
</dependency>

Insert picture description here

Supporting video address for the explanation of the crazy god: https://www.bilibili.com/video/BV1Y441197Lw

Reference

Guess you like

Origin blog.csdn.net/qq_40649503/article/details/109494477