SpringBoot - Integrate Swagger

Project integration Swagger

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

  • Backend -> backend control layer, service layer, data access layer

  • Front-end and back-end interact through API

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

resulting problems

  • Front-end and back-end integration, the front-end or back-end cannot achieve "timely negotiation and early resolution", which eventually leads to a concentrated outbreak of problems

solution

  • First define the schema [outline of the plan] and track the latest APIs in real time, reducing integration risks

Swagger

  • The most popular API framework in the world

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

  • Run it directly, test the API online

  • Supports multiple languages ​​(eg: Java, PHP, etc.)

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

SpringBoot integrates Swagger

SpringBoot integrates Swagger => springfox , two jar packages

  • Springfox-swagger2
  • swagger-springmvc

Using Swagger

Requirement: jdk 1.8+ otherwise swagger2 will not work

step:

1. Create a new SpringBoot-web project

2. Add Maven dependencies

      <!-- 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 HelloController and test to make sure it runs successfully!

@RestController
public class HelloController {
    
    

    @RequestMapping(value = "/hello")
    public String hello(){
    
    
        return "hello";
    }

}

4. To use Swagger, we need to write a configuration class - SwaggerConfig to configure Swagger

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

5. Access test: http://localhost:8080/swagger-ui.html , you can see the interface of swagger;

img

Startup failed to drop the springboot version to 2.5.7

img

Configure Swagger

1. The Swagger instance bean is a Docket, so configure Swaggger by configuring a Docket instance.

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

2. Document information can be configured through the apiInfo() property

//配置文档信息
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. The Docket instance is associated with apiInfo()

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

4. Restart the project and visit the test http://localhost:8080/swagger-ui.html to see the effect;

Configure scan interface

1. Configure how to scan the interface through the select() method when building a Docket.

@Bean
public Docket docket() {
    
    
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
      .apis(RequestHandlerSelectors.basePackage("com.kwok.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 scan interface through the package path, you can also scan the interface by configuring other methods. 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.kwok.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kwok/**"))
      .build();
}

5. The optional values ​​here are also

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

img

Configure Swagger switches

1. Configure whether to enable swagger through the enable() method. If it is false, swagger will 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.kwok.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kwok/**"))
      .build();
}

2. How to dynamically configure swagger to be displayed when the project is in test and dev environments, but not in pro?

@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.kwok.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kwok/**"))
      .build();
}

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

img

img

img

img

img

Configure API document grouping

1. If no grouping is configured, the default is default. Groups can be configured through the groupName() 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 dockets:

@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 class configuration

1. Create a new entity class

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

    public User() {
    
    
    }

    public User(String username, String password) {
    
    
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

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

@RestController
public class HelloController {
    
    

    @GetMapping(value = "/hello")
    public String hello(){
    
    
        return "hello";
    }

    // 只要我们的接口中,返回值存在实体类,他就会被扫描到swagger中
    @PostMapping(value = "/user")
    public User user(){
    
    
        return new User();
    }

    // Operation接口
    @ApiOperation("Hello控制类")
    @GetMapping(value = "/sayhello")
    public String hello(@ApiParam("用户名") String username){
    
    
        return "hello"+username;
    }

    @ApiOperation("Post测试")
    @PostMapping(value = "/posttest")
    public User posttest(@ApiParam("用户名") User user){
    
    
        return user;
    }

}

3. Restart to view the test

img

Note: It is not because of the @ApiModel annotation that the entity is displayed here, but as long as the entity that appears on the return value of the interface method will be displayed here, and the two annotations @ApiModel and @ApiModelProperty are just for adding annotations to entities .

@ApiModel annotates a class

@ApiModelProperty annotates class properties

Common Notes

All annotations of Swagger are defined under the io.swagger.annotations package

The following are some frequently used ones, and those not listed can be referred to separately:

Swagger annotations Simple
@Api(tags = "xxx module description") Acts on module classes
@ApiOperation("xxx interface description") Acts on interface methods
@ApiModel("xxxPOJO description") Acts on model classes: such as VO, BO
@ApiModelProperty(value = "xxx property description", hidden = true) Acting on class methods and properties, setting hidden to true can hide the property
@ApiParam("xxx parameter description") Acts on parameters, methods and fields, similar to @ApiModelProperty

We can also configure some annotations for the requested interface

@ApiOperation("Post测试")
@PostMapping(value = "/posttest")
public User posttest(@ApiParam("用户名") User user){
    
    
    return user;
}

Can be tested online

img

  In this way, you can add some configuration information to some difficult-to-understand properties or interfaces to make it easier to read!

  Compared with the traditional Postman or Curl way to test the interface, using swagger is simply a fool's operation, no additional documentation is required (well written is a document itself) and it is less prone to errors, just enter the data and click Execute, if you cooperate again It can be said that the automation framework basically does not require human operation.

  Swagger is an excellent tool. Now many small and medium-sized Internet companies in China are using it. Compared with the traditional method of first publishing Word interface documents and then testing, this is obviously more in line with the current rapid iterative development market. Of course, remind everyone to remember to close Swagger in the formal environment, firstly for security reasons, and secondly, it can also save runtime memory.

Expansion: other skins

We can import different packages to implement different skin definitions:

1. By default visit http://localhost:8080/swagger-ui.html

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

img

2. Bootstrap-ui access http://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>

img

3. Layui-ui access http://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>

img

4. mg-ui access http://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>

img

Guess you like

Origin blog.csdn.net/qq_41355222/article/details/123966655