美文网首页Java软件开发技术
springboot+springfox-swagger-ui

springboot+springfox-swagger-ui

作者: 编程永无止境 | 来源:发表于2021-09-22 08:48 被阅读0次

    1、简介

    源码地址:https://github.com/springfox/springfox

    帮助文档:

    http://springfox.github.io/springfox/

    http://springfox.github.io/springfox/docs/current/

    swagger是一个非常流行的文档自动生成工具,可以与多种编程语言结合使用,在Java编程中通常可以结合依赖jar包,让swqgger生成springboot的API文档。

    Swagger-ui3在前一个版本上做了很大的改进。

    官网描述:

    Migrating from earlier snapshot
    Spring Boot Applications
    
    NOTE: Would love feedback to make this better
    1. Remove explicit dependencies on `springfox-swagger2`
    2. Remove any `@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上的显式依赖
    2.删除了任何的 @EnableSwagger2 注解
    3.添加了 springfox-boot-starter 作为新的依赖项
    4.还有些Springfox3.x删除了对guava和其他第三方库的依赖(取决于spring插件)并为注释和模型打开api库),因此如果使用guava谓词/函数,则需要转换到Java8函数接口。

    2、基本使用步骤

    2.1.添加依赖

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
    

    2.2.启动SpringBoot程序然后打开浏览器

    swagger ui 3.0会自动扫描当前程序的所有控制器、以及业务类和实体类

    默认的访问地址是:

    ``http://host/swagger-ui/index.html`

    或者

    http://host/swagger-ui/

    image-20210916104219793.png

    2.3.使用账号和密码访问API

    添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    

    修改配置

    spring:
      security:
        user:
          name: ts   # 配置用户名
          password: 123456      #密码
    

    创建一个配置类

    package com.ts.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    /**
     * 配置Swagger的校验
     * @Author zhouqian
     * @Description //TODO somken
     * @Date 13:13 2021/9/16
     **/
    @Configuration
    @EnableWebSecurity
    public class ActuatorWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                //普通的接口不需要校验
                .antMatchers("/user/**").permitAll()
                // swagger页面需要添加登录校验
                .antMatchers("/swagger-ui/index.html").authenticated()
                .and()
                .formLogin();
        }
    }
    
    

    3、常用注解

    我们在使用Swagger UI3的使用除了SpringMVC提供的注解,还需要使用以下注解描述接口:

    • @Api()用于类名
    • @ApiOperation()用于方法名
    • @ApiParam()用于参数说明
    • @ApiModel()用于实体类
    • @ApiModelProperty用于实体类属性

    示例:

    package com.ts.controller;
    
    import cn.hutool.core.util.StrUtil;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.toolkit.Wrappers;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.ts.common.Result;
    import com.ts.mapper.UserMapper;
    import com.ts.pojo.User;
    import io.swagger.annotations.*;
    import io.swagger.v3.oas.annotations.responses.ApiResponse;
    import org.springframework.web.bind.annotation.*;
    
    import javax.annotation.Resource;
    
    /**
     * 用户控制器
     * @Author zhouqian
     * @Description
     * @Date 10:22 2021/9/15
     **/
    
    @Api(tags = "用户控制器")
    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        @Resource
        private UserMapper userMapper;
    
        /**
         * 用户分页
         * https://hutool.cn/
         * @param pageNum Integer
         * @param pageSize Integer
         * @param search String
         * @return Result
         */
        @ApiOperation(value = "用户查询分页", notes = "这是一个用户查询分页功能")
        @ApiImplicitParams(value = {
                @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "Integer"),
                @ApiImplicitParam(name = "pageSize", value = "每页显示的数量", paramType = "Integer"),
                @ApiImplicitParam(name = "search", value = "查询字符串", paramType = "String")
        })
        @GetMapping
        public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  @RequestParam(defaultValue = "") String search){
    
            //分页查询
            /*Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize),
                    Wrappers.<User>lambdaQuery().like(User::getNickName, search));*/
    
            //处理空值,这里使用了hutool的工具
            LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery();
            if (StrUtil.isNotBlank(search)) {
                queryWrapper.like(User::getNickName, search);
            }
            Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize),queryWrapper);
    
            return Result.success(userPage);
        }
    }
    
    

    4、自定义访问路径

    4.1、针对WebMvc

    编写一个配置类 SwagggerUIWebMvcConfigurer.java

    package springfox.boot.starter.autoconfigure;
    
    import org.springframework.util.StringUtils;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    // tag::swagger-ui-configurer[]
    public class SwaggerUiWebMvcConfigurer implements WebMvcConfigurer {
      private final String baseUrl;
    
      public SwaggerUiWebMvcConfigurer(String baseUrl) {
        this.baseUrl = baseUrl;
      }
    
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String baseUrl = StringUtils.trimTrailingCharacter(this.baseUrl, '/');
        registry.
            addResourceHandler(baseUrl + "/swagger-ui/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
            .resourceChain(false);
      }
    
      @Override
      public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController(baseUrl + "/swagger-ui/")
            .setViewName("forward:" + baseUrl + "/swagger-ui/index.html");
      }
    }
    // end::swagger-ui-configurer[]
    

    4.2、针对WebFlux

    一样编写一个配置类

    package springfox.boot.starter.autoconfigure;
    
    import org.springframework.util.StringUtils;
    import org.springframework.web.reactive.config.ResourceHandlerRegistry;
    import org.springframework.web.reactive.config.WebFluxConfigurer;
    
    // tag::swagger-ui-configurer[]
    public class SwaggerUiWebFluxConfigurer implements WebFluxConfigurer {
      private final String baseUrl;
    
      public SwaggerUiWebFluxConfigurer(String baseUrl) {
        this.baseUrl = baseUrl;
      }
    
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String baseUrl = StringUtils.trimTrailingCharacter(this.baseUrl, '/');
        registry.
            addResourceHandler(baseUrl + "/swagger-ui/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
            .resourceChain(false);
      }
    }
    // end::swagger-ui-configurer[]
    

    5、生成本地文档

    如果想要使用 Swagger UI生成本地的文档需要使用gradle

    5.1、代码检查

    代码覆盖,检查型

    ./gradlew check
    

    5.2、构建参考文档

    要构建所有当前文档(构建手写文档和 javadocs):

    ./gradlew allDocs
    

    文档在文件夹中生成。发布当前文档(快照)build/all-docs

    ./gradlew releaseDocs
    

    相关文章

      网友评论

        本文标题:springboot+springfox-swagger-ui

        本文链接:https://www.haomeiwen.com/subject/laewgltx.html