Spring Boot 集成新版 Swagger2 (starter方式)

一、 了解官方最新资料

截止到 2021年04月,Springfox 的 Swagger2 依赖版本最高到 3.0.0。
但至少在 2.10.5 版本就已经有了不少变化,比如找不到 @EnableSwagger2 的注解了等等。
先到Springfox GH地址:https://github.com/springfox/springfox

看 Getting Started, 终于有 swagger 的 starter 了, Spring Boot 用户更方便集成了

可以看到主要变动:

  1. Remove explicit dependencies on springfox-swagger2
  2. Remove the @EnableSwagger2 annotations
  3. Add the springfox-boot-starter dependency
  4. Springfox 3.x removes dependencies on guava and other 3rd party libraries (not zero dep yet! depends on spring plugin and open api libraries for annotations and models) so if you used guava predicates/functions those will need to transition to java 8 function interfaces

大意为

  1. 移除 springfox-swagger2 的显式依赖 (个人理解是用新的依赖不需要添加这个旧的 springfox-swagger2 依赖了)
  2. 移除了 @EnableSwagger2 注解 (这是与之前版本明显区别的地方)
  3. 新增了 starter 方式的依赖
  4. Springfox 3.x 版本移除了 guava 和其它一些第三方库 (不过尚未完全移除), 如果使用 guava 库的断言/函数式接口功能的需要过渡到 java 8 的函数式接口

二、记录新的集成方式

1. POM

大部分内容依然没变,唯一不同的是依赖。与 Springboot 集成可用新的依赖:

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
2. 配置类

SwaggerConfig.java(不需要 @EnableSwagger2 了)

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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("org.example.consumer.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    /**
     * Api 文档详细信息
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Title")
                .contact(new Contact("name", "url", "email"))
                .version("1.0.0")
                .description("description")
                .build();
    }
}

最简配置只需以上两步即可。

URL: http://127.0.0.1:8990/swagger-ui/index.html

(8990 是我配置的项目端口)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值