springboot-swagger使用

简介: springboot-swagger使用

引入

  implementation('io.springfox:springfox-swagger2:2.9.2')
  implementation('io.springfox:springfox-swagger-ui:2.9.2')

Config

BaseSwaggerConfig
package com.blove.ityustudy.config;

import io.swagger.annotations.ApiOperation;
import  springfox.documentation.service.Parameter;
import org.springframework.context.annotation.Bean;

import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 文档配置
 *
 * @author lihe
 */
public abstract class BaseSwaggerConfig {


    private final static String TOKEN = "token";
    private final static String DEVICE_NO = "deviceNo";
    private final static String USER_ID = "userId";

    private final static String PASS_AS = "header";



    /**
     * 子类用于自定义接口参数
     *
     * @return api 配置
     */
    protected abstract ApiInfo apiInfo();


    @Bean
    public Docket createRestApi() {
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        Parameter parameter = ticketPar.name("Authorization").description("用户信息")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();//header中的ticket参数非必填,传空也可以
        pars.add(parameter);    //根据每个方法名也知道当前方法在设置什么参数

        List<SecurityContext> data = new ArrayList();
        data.add(securityContext());
        return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(security())
                .securityContexts(data)
                .apiInfo(apiInfo())
                .globalOperationParameters(pars)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }


    private Stream<String> getKeyStream(){
        return Stream.of(TOKEN, DEVICE_NO, USER_ID);
    }


    private List<ApiKey> security() {
        return  this.getKeyStream()
                .map(x -> new ApiKey(x, x, PASS_AS))
                .collect(Collectors.toList());
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any())
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope
                = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return this.getKeyStream()
                .map(x -> new SecurityReference(x, authorizationScopes))
                .collect(Collectors.toList());
    }
}

Swagger2
package com.blove.ityustudy.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class Swagger2  extends BaseSwaggerConfig{

    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     *
     * @return
     */
    @Override
    protected ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Ma-vendor-api")
                .description("Ma-vendor-api")
                .termsOfServiceUrl("http://www.build.com")
                .version("1.0.0")
                .build();
    }
}


使用

方法使用
  @ApiOperation(value = "获取用户信息")
    @ApiImplicitParams({ // 参数说明
            @ApiImplicitParam(name = "name", paramType = "query", value = "用户名字", dataType = "string", required = true),
            @ApiImplicitParam(name = "sex", paramType = "query", value = "性别", dataType = "Integer"),
            @ApiImplicitParam(name = "city", paramType = "query", value = "城市", dataType = "string"),
    })
    @PostMapping(value = "/getUser")
    @LimitIp(ip = "47.91.23.212")
    public R<UserModel> getUser(@RequestParam(value = "name") String name, @RequestParam(value = "sex", required = false) Integer sex, @RequestParam(value = "city", required = false) String city) {
        if (!StringUtils.isBlank(city)) {
            return RUtil.ok(new UserModel().setName(name).setAge(sex).setCity(city));
        }
        throw new CommonException("城市不能为空");
    }
属性使用
 @ApiModelProperty(value="状态吗",name="code",example="0")
    public int code;
    @ApiModelProperty(value="错误信息",name="msg",example="密码不对")
    public String msg;
    @ApiModelProperty(value="对象信息",name="data",example="")
    public T data;
类使用
@Data
@ApiModel(value="R",description="统一数据信息")
public class R<T> implements Serializable{
    @ApiModelProperty(value="状态吗",name="code",example="0")
    public int code;
    @ApiModelProperty(value="错误信息",name="msg",example="密码不对")
    public String msg;
    @ApiModelProperty(value="对象信息",name="data",example="")
    public T data;


}
相关文章
|
7月前
|
Java API Spring
【一】springboot整合swagger
【一】springboot整合swagger
82 0
|
7月前
|
XML Java 测试技术
【二】springboot整合自定义swagger
【二】springboot整合自定义swagger
75 0
|
7月前
|
Java API
SpringBoot 整合swagger3.X
SpringBoot 整合swagger3.X
261 0
|
4月前
|
Java API Spring
springboot集成swagger
这篇文章介绍了如何在Spring Boot项目中集成Swagger 2.10.0来生成API文档,包括添加依赖、编写配置类、创建接口文档,并使用Knife4j美化Swagger界面。
|
4月前
|
Java
SpringBoot 配置 Swagger
SpringBoot 配置 Swagger
41 0
|
5月前
|
Java 测试技术 API
|
前端开发 Java API
springboot 集成swagger
springboot 集成swagger
121 0
|
前端开发 测试技术 API
SpringBoot-25-SpringBoot整合Swagger2以及Swagger-Bootstrap-Ui的使用
我们在之前的文章中讲过了RESTful风格设计API,没有看过的小伙伴可以查找之前的文章看一下,那么在针对这些API我们需要怎么进行测试呢?也许你会说你通过单元测试、postman、IDEA的http client
87 0
|
Java
Springboot 整合 Swagger 3
Springboot 整合 Swagger 3
216 0
|
API
springboot04、swagger配置
springboot04、swagger配置
153 0
springboot04、swagger配置