基于springboot 2.2.x & swagger 3.0

依赖

  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-boot-starter</artifactId>
  4. <version>3.0.0</version>
  5. </dependency>

配置

  1. @Configuration
  2. public class SwaggerConfig {
  3. @Bean
  4. public Docket createRestApi() {
  5. return new Docket(DocumentationType.OAS_30)
  6. .apiInfo(apiInfo())
  7. // 是否开启
  8. .enable(true)
  9. .select()
  10. .apis(RequestHandlerSelectors.basePackage("com.logic.transocean"))
  11. .paths(PathSelectors.any())
  12. .build();
  13. }
  14. private ApiInfo apiInfo() {
  15. return new ApiInfoBuilder()
  16. .title("transocean")
  17. //创建人
  18. .contact(new Contact("jack.zhou", "", "jacketzc@foxmail.conm"))
  19. .version("1.0")
  20. .description("")
  21. .build();
  22. }
  23. }

常用注解

@Api

用于Controller,描述api信息

  • 要用tags,默认的值好像不太管用

    1. @Api(tags = "授权中心")
    2. @RequestMapping("/oauth")
    3. @RestController
    4. public class OAuthController{}

    @ApiOperation

    用于Controller的method,描述api信息

    1. @ApiOperation("获取授权")
    2. @PostMapping("/authorize")
    3. public Response authorize(@RequestBody OAuthRequestDTO oAuthRequestDTO) {
    4. return ResponseUtil.returnSuccess(oauthService.authorize(oAuthRequestDTO));
    5. }

    @ApiModel

    用于实体

    1. @ApiModel(description = "oauth请求参数")
    2. @Data
    3. public class OAuthRequestDTO {}

    @ApiModelProperty

    用于实体的属性

    1. @ApiModelProperty("客户端id")
    2. private String client_id;

    效果

    image.png

    更换第三方ui

    这边就以knife4j为例,直接引入就好了,它已经包含了swagger的依赖,配置和上面一样的

    1. <dependency>
    2. <groupId>com.github.xiaoymin</groupId>
    3. <artifactId>knife4j-spring-boot-starter</artifactId>
    4. <version>3.0.3</version>
    5. </dependency>

    看起来确实更友好一点:
    image.png

    常见问题与解决方法

    doc.html 404

    看看有些配置类是不是继承WebMvcConfigurationSupport的,应该改成实现WebMvcConfigurer接口

  • 事实上,不建议继承WebMvcConfigurationSupport去定义配置,因为该操作会使得原有的自动配置失效,观察mvc自动配置的注解就可以知道:

    1. // 如果自定义了WebMvcConfigurationSupport的bean,则默认配置就不生效了
    2. @ConditionalOnMissingBean(WebMvcConfigurationSuport.class)
    3. public class WebMvcAutoConfiguration{}

    springboot 2.6.x启动报错

    添加以下配置(治标不治本):spring.mvc.pathmatch.matching-strategy=ant_path_matcher