天天看點

springfox-swagger-ui3的基本使用spring+springfox-swagger-ui 3線上API文檔的基本使用

spring+springfox-swagger-ui 3線上API文檔的基本使用

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/

springfox-swagger-ui3的基本使用spring+springfox-swagger-ui 3線上API文檔的基本使用

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 zq
 * @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 zq
 * @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