Spring Boot 接入swagger3.0和Knife4j

Spring Boot 接入swagger3.0和Knife4j

一、Spring Boot 项目初始化
  1. 创建项目

    在这里插入图片描述

    在这里插入图片描述

  2. 编写controller

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class TestController {
        @GetMapping(value = "/say")
        public String sayHello(){
            return "hello spring";
        }
    }
    
  3. 测试结果

    1、浏览器访问:http://localhost:8080/say
    2、输出显示:hello spring
    
二、项目启动demo界面定制
  • 生成定制化字符串——文字banner

    在线工具:
    1、http://www.patorjk.com/software/taag/
    2、http://www.network-science.de/ascii/
    
                              _
                             | |
     ___ _ __ ___   __ _ _ __| |_    _ __ ___   ___   ___  _ __
    / __| '_ ` _ \ / _` | '__| __|  | '_ ` _ \ / _ \ / _ \| '_ \
    \__ \ | | | | | (_| | |  | |_   | | | | | | (_) | (_) | | | |
    |___/_| |_| |_|\__,_|_|   \__|  |_| |_| |_|\___/ \___/|_| |_|
    
    
    
  • 配置

    1、将上述字符串写入文件banner.txt
    2、将文件存放在项目路径resource目录下即可
    

    启动效果:

    在这里插入图片描述

三、接入swagger3.0案例
  1. swagger3.0简介

    Swagger 是一套基于 OpenAPI 规范(OpenAPI Specification,OAS)构建的开源工具,可以帮助我们设计、构建、记录以及使用 Rest API,可以将 Controller 的方法以文档的形式展现。

    新特性:

    • Remove explicit dependencies on springfox-swagger2
    • Remove any @EnableSwagger2… annotations
    • Add the springfox-boot-starter dependency
    • 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.
  2. 引入配置

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
    
    # application.yml配置文件
    # 项目名称配置
    spring:
      application:
        name: smart-moon
    # 服务端口配置
    server:
      port: 8080
    # swagger配置 
    swagger:
      enable: true
      application-name: ${spring.application.name}
      application-version: 1.0
      application-description: springfox swagger 3.0
      try-host: http://localhost:${server.port}
    
  3. 测试用例

    自定义配置加载类

    
    @Component
    @ConfigurationProperties("swagger")
    public class SwaggerProperties {
        /**
         * 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
         */
        private Boolean enable;
    
        /**
         * 项目应用名
         */
        private String applicationName;
    
        /**
         * 项目版本信息
         */
        private String applicationVersion;
    
        /**
         * 项目描述信息
         */
        private String applicationDescription;
    
        /**
         * 接口调试地址
         */
        private String tryHost;
    
        public Boolean getEnable() {
            return enable;
        }
    
        public void setEnable(Boolean enable) {
            this.enable = enable;
        }
    
        public String getApplicationName() {
            return applicationName;
        }
    
        public void setApplicationName(String applicationName) {
            this.applicationName = applicationName;
        }
    
        public String getApplicationVersion() {
            return applicationVersion;
        }
    
        public void setApplicationVersion(String applicationVersion) {
            this.applicationVersion = applicationVersion;
        }
    
        public String getApplicationDescription() {
            return applicationDescription;
        }
    
        public void setApplicationDescription(String applicationDescription) {
            this.applicationDescription = applicationDescription;
        }
    
        public String getTryHost() {
            return tryHost;
        }
    
        public void setTryHost(String tryHost) {
            this.tryHost = tryHost;
        }
    }
    
    

    配置初始化,基于自定义配置类模板初始化完整swagger配置

    
    @Configuration
    public class SwaggerConfiguration implements WebMvcConfigurer {
        private final SwaggerProperties swaggerProperties;
    
        public SwaggerConfiguration(SwaggerProperties swaggerProperties) {
            this.swaggerProperties = swaggerProperties;
        }
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.OAS_30).pathMapping("/")
    
                    // 定义是否开启swagger,false为关闭,可以通过变量控制
                    .enable(swaggerProperties.getEnable())
    
                    // 将api的元信息设置为包含在json ResourceListing响应中。
                    .apiInfo(apiInfo())
    
                    // 接口调试地址
                    .host(swaggerProperties.getTryHost())
    
                    // 选择哪些接口作为swagger的doc发布
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
    
                    // 支持的通讯协议集合
                    .protocols(newHashSet("https", "http"))
    
                    // 授权信息设置,必要的header token等认证信息
                    .securitySchemes(securitySchemes())
    
                    // 授权信息全局应用
                    .securityContexts(securityContexts());
        }
    
        /**
         * API 页面上半部分展示信息
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder().title(swaggerProperties.getApplicationName() + " Api Doc")
                    .description(swaggerProperties.getApplicationDescription())
                    .contact(new Contact("swagger3.0", null, "xxxxx@qq.com"))
                    .version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion())
                    .build();
        }
    
        /**
         * 设置授权信息
         */
        private List<SecurityScheme> securitySchemes() {
            ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
            return Collections.singletonList(apiKey);
        }
    
        /**
         * 授权信息全局应用
         */
        private List<SecurityContext> securityContexts() {
            return Collections.singletonList(
                    SecurityContext.builder()
                            .securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
                            .build()
            );
        }
    
        @SafeVarargs
        private final <T> Set<T> newHashSet(T... ts) {
            if (ts.length > 0) {
                return new LinkedHashSet<>(Arrays.asList(ts));
            }
            return null;
        }
    
        /**
         * 通用拦截器排除swagger设置,所有拦截器都会自动加swagger相关的资源排除信息
         */
        @SuppressWarnings("unchecked")
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            try {
                Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
                List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
                if (registrations != null) {
                    for (InterceptorRegistration interceptorRegistration : registrations) {
                        interceptorRegistration
                                .excludePathPatterns("/swagger**/**")
                                .excludePathPatterns("/webjars/**")
                                .excludePathPatterns("/v3/**")
                                .excludePathPatterns("/doc.html");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    
    

    编写controller

    
    @EnableOpenApi // 也可以不写此注解
    @Api(tags="账户管理-swagger3.0")
    @RestController
    @RequestMapping("/admin/list/user")
    public class MyController {
    
        @ApiOperation(value = "账户列表")
        @GetMapping
        public List<String> list(){
            return List.of("张三","李四","爱丽丝");
        }
    
        @ApiOperation(value = "根据ID删除用户")
        @DeleteMapping("{id}")
        public boolean removeById(
                @ApiParam(name = "id", value = "用户id", required = true)
                @PathVariable String id){
            return true;
        }
    }
    
    
    

    效果:Swagger UI

    在这里插入图片描述

四、接入Knife4j案例
  1. Knife4j简介

    Knife4j的前身是swagger-bootstrap-ui,前身swagger-bootstrap-ui是一个纯swagger-uiui皮肤项目,Knife4j不仅仅将前身的Ui皮肤通过Vue技术栈进行了重写,也增加了更多个性化的特性增强功能,基于springfox项目以及OpenAPI的规范,为用户提供了更加丰富的体验。

  2. 引入配置

    <dependency>
         <groupId>com.github.xiaoymin</groupId>
         <artifactId>knife4j-spring-boot-starter</artifactId>
         <version>3.0.3</version>
    </dependency>
    
  3. 测试用例

    • 1.创建Swagger配置依赖:

      
      @Configuration
      @EnableSwagger2
      public class Knife4jConfiguration {
      
          @Value("${swagger.enable}")
          private Boolean enable;
      
          @Bean(value = "defaultApi2")
          public Docket defaultApi2() {
              Docket docket=new Docket(DocumentationType.SWAGGER_2)
                      .enable(enable)
                      .apiInfo(
                              new ApiInfoBuilder()
                                      //.title("swagger-bootstrap-ui-demo RESTful APIs")
                                      .description("# swagger-bootstrap-ui-demo restful APIs")
                                      .termsOfServiceUrl("http://www.xx.com/")
                                      .contact(new Contact("管理员", "http://www.xx.com/", "xxxx@qq.com"))
                                      .version("1.0")
                                      .build()
                      )
                      //分组名称
                      .groupName("2.0版本")
                      .select()
                      //这里指定你自己的Controller扫描包路径
                      .apis(RequestHandlerSelectors.basePackage("com.example.smartmoon.controller"))
                      .paths(PathSelectors.any())
                      .build();
              return docket;
          }
      }
      
      
    • 2.编写controller实现一个简单的restful接口

      @RestController
      @RequestMapping(value = "/api/v2/user", produces = MediaType.APPLICATION_JSON_VALUE)
      @Api(tags = "用户管理")
      public class UserController {
      
          @GetMapping
          @ApiOperation(value = "分页查询-1")
          public String page(){
              return "测试分页查询";
          }
      
          @GetMapping("/haha")
          @ApiOperation(value = "分页查询-2")
          public List<UserEntity> getData(){
              List<UserEntity> list = new ArrayList<>();
              list.add(new UserEntity().setName("花花").setSex("男"));
              list.add(new UserEntity().setName("小王").setSex("女"));
              return list;
          }
      }
      
      
      @Data
      @Accessors(chain = true)
      @ApiModel
      public class UserEntity {
      
          @ApiModelProperty("名称")
          private String name;
          @ApiModelProperty("性别")
          private String sex;
      }
      
      
    • 3.运行效果

      在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玉言心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值