SpringBoot快速入门-SpringBoot 2.6.x系列的Swagger2配置

1、引入pom

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

2、添加Swagger配置类

import io.swagger.annotations.Api;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * IT之美 Swagger配置类
 */
@Configuration
@EnableSwagger2
public class Swagger {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(true)          // 是否禁用swagger
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger API文档")
                .description("接口文档")
                .version("1.0")
                .build();
    }
}

3、添加Controller

import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Hello world!
 *
 */
@Api(tags = "Hello World App1")
@RestController
public class ApiController1
{

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }

}

4、修改配置属性
在springboot2.6.2中将SpringMVC默认路径匹配策略从AntPathMatcher更改为PathPatternParser,如果像SpringBoot2.5.x系列,配置好上面的代码就可以直接使用了。
但是在2.6.x系列,启动服务会报错,解决办法是切换回原先的AntPathMatcher,在yml文件中添加一下配置:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

5、启动应用程序

6、查看文档
localhost:8081/swagger-ui.html#/

页面输出:
==========================
测试接口文档

Hello World App1 Api Controller 1

GET
/hello	hello
==========================