springboot整合swagger2

  swagger是一个不错的接口生成工具,而且其UI界面可以查看以及测试接口。

  之前前后端分离的时候是将文档写在docx中,然后自己测试用postman进行测试。确实比较浪费时间。

1.简单的整合

1.增加配置文件:

package com.zd.bx.config.swapper2;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
// 是否开启swagger,正式环境一般是需要关闭的(避免不必要的漏洞暴露!),可根据springboot的多环境配置进行设置
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2Configure implements WebMvcConfigurer {

    // swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                // 为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.zd.bx.controller")).paths(PathSelectors.any()).build();
    }

    // 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 页面标题
                .title("XXX软件接口描述")
                // 创建人信息
                .contact(new Contact("张三", "https://www.baidu.com/", "zhangsan@qq.com"))
                // 版本号
                .version("1.0")
                // 描述
                .description("API 描述").build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

2.application.properties激活swagger2

#是否激活 swagger true or false
swagger.enable=true

如果有拦截器或者权限过滤器需要放行swagger相关请求:

例如我的shiro权限配置如下:

        FILTER_CHAIN_DEFINITION_MAP.put("/swagger-ui.html", "anon"); // swagger放开
        FILTER_CHAIN_DEFINITION_MAP.put("/webjars/**", "anon"); // swagger请求的资源放开
        FILTER_CHAIN_DEFINITION_MAP.put("/swagger-resources/**", "anon"); // swagger请求的资源放开
        FILTER_CHAIN_DEFINITION_MAP.put("/v2/api-docs/**", "anon"); // swagger请求的资源放开

 3. 启动应用访问:

2.注解使用

1.@Api  修饰类

// tags:说明该类的作用,可以在UI界面上看到的注解,value=该参数没什么意义、在UI界面上也看到
@Api(tags = { "用户接口" })
public class UserController extends AbstractController<User, Long> {

如下:

2.@ApiOperation 方法描述

3.@ApiResponses、@ApiResponse修饰返回值信息

4.@ApiImplicitParam 参数描述

5.@ApiModel、@ApiModelProperty  修饰请求的参数和返回参数的信息(用于JSON请求参数和返回值)

例如:

    @GetMapping("/detail/{id}")
    // 方法描述
    @ApiOperation(value = "详情", notes = "查询详情")
    // 返回信息描述
    @ApiResponses({ @ApiResponse(code = -1, message = "请求正确") })
    // 参数描述
    @ApiImplicitParam(name = "id", value = "请求的ID", required = true)
    public JSONResultUtil<T> detail(@PathVariable() E id, HttpServletRequest request) {
        T bean = getBaseService().selectById(id);
        ValidateUtils.isTrue(bean != null, "u100003");

        return JSONResultUtil.successWithMsgAndData("ok", bean);
    }

结果:

 

 3. 如果希望在用UI请求的时候携带参数,比如cookie、header等参数

package com.zd.bx.config.swapper2;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.zd.bx.utils.constant.DefaultValue;

import springfox.documentation.builders.ApiInfoBuilder;
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.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
// 是否开启swagger,正式环境一般是需要关闭的(避免不必要的漏洞暴露!),可根据springboot的多环境配置进行设置
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2Configure implements WebMvcConfigurer {

    // swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
    @Bean
    public Docket createRestApi() {
        // 增加请求头配置
        ParameterBuilder params = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        // 设置参数的名字以及类型:可以是cookie、header等信息
        Parameter access_token = new ParameterBuilder().name(DefaultValue.TOKEN_KEY).description("access_token")
                .modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        Parameter belong_database = new ParameterBuilder().name(DefaultValue.DATABASE_NAME_KEY)
                .description("belong_database").modelRef(new ModelRef("string")).parameterType("header").required(false)
                .build();
        pars.add(access_token);
        pars.add(belong_database);

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.zd.bx.controller")).paths(PathSelectors.any()).build()
                .globalOperationParameters(pars);

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 页面标题
                .title("XXX软件接口描述")
                // 创建人信息
                .contact(new Contact("张三", "https://www.baidu.com/", "zhangsan@qq.com"))
                // 版本号
                .version("1.0")
                // 描述
                .description("API 描述").build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

结果:

补充:swagger2生成所有类型的请求文档,如下:

 原因是我们没有指定请求方式,也就是 @RequestMapping 没有指定methos。解决办法:直接用@PostMapping或者指定method。

 补充:swagger2也可以对指定的包或者包含某注解的类进行生成API

    @Bean
    public Docket createRestApi() {
        // 增加请求头配置
        ParameterBuilder params = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        // 设置参数的名字以及类型:可以是cookie、header等信息
        Parameter access_token = new ParameterBuilder().name(DefaultValue.TOKEN_KEY).description("access_token")
                .modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        Parameter belong_database = new ParameterBuilder().name(DefaultValue.DATABASE_NAME_KEY)
                .description("belong_database").modelRef(new ModelRef("string")).parameterType("header").required(false)
                .build();
        pars.add(access_token);
        pars.add(belong_database);

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                // 为任何接口生成API文档
                .apis(RequestHandlerSelectors.any())
                // 指定包生成API文档
                // .apis(RequestHandlerSelectors.basePackage("com.zd.bx.controller"))
                // 为有@ApiOperation注解的方法生成API文档
                // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 为有@Api注解的Controller生成API文档
                // .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any()).build().globalOperationParameters(pars);
    }
原文地址:https://www.cnblogs.com/qlqwjy/p/13373380.html