美文网首页Java
Springboot2.3.0集成swagger2.9.2

Springboot2.3.0集成swagger2.9.2

作者: shadow_2155 | 来源:发表于2021-02-06 20:45 被阅读0次

一、导入依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

二、创建swagger配置

  在Application.java同级,创建Swagger2的配置类Swagger2:

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Value("${swagger.enable}")
    private Boolean enable;

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Api接口")
                .description("Api接口的描述")
                .termsOfServiceUrl("http://www.baidu.com/")
                .version("1.0")
                .build();
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.controller"))
                .paths(PathSelectors.any())
                .build()
                .enable(enable);
    }
}

@ Configuration:spring boot 加载配置。
@EnableSwagger2:启用Swagger2。
createRestApi():创建Api的基本信息。RequestHandlerSelectors.basePackage是通过扫描该路径下的所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
.enable(enable):通过配置文件控制swagger2是否启用。在配置文件中配置swagger.enable为“true”或“false”。一般正式环境会关闭swagger功能。

三、配置资源路径

  如果继承了WebMvcConfigurationSupport,则需要重新指定静态资源(不配置的话会报No mapping for GET /swagger-ui.html错误):

@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {

    private MyInterceptor myInterceptor;

    @Autowired
    public CorsConfig (MyInterceptor myInterceptor){
        this.myInterceptor = myInterceptor;
    }

    // 注册过滤器
    @Bean
    public FilterRegistrationBean<RepeatedlyReadFilter> repeatedlyReadFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        RepeatedlyReadFilter repeatedlyReadFilter = new RepeatedlyReadFilter();
        registration.setFilter(repeatedlyReadFilter);
        registration.addUrlPatterns("/*");
        return registration;
    }


    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }

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

四、添加接口文档内容

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import com.xyf.scriptkill.util.RestMessage;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;

@Api(tags="测试控制器")
@RestController
public class TestController {

    @ApiOperation(value="测试get", notes="")
    @ApiImplicitParams({
            @ApiImplicitParam(name="name",value="姓名",required=true,paramType="query"),
            @ApiImplicitParam(name="address",value="地址",required=true,paramType="query"),
    })
    @GetMapping("/api/gettest")
    public RestMessage getTest(
            @RequestParam(value = "name", required = true) String name,
            @RequestParam(value = "address", required = true) String address
    ){
        RestMessage restMessage = new RestMessage();
        restMessage.setSuccess(true);
        restMessage.setMessage("返回成功!");
        restMessage.setData(null);
        restMessage.setCode(HttpStatus.HTTP_OK);
        return restMessage;
    }

    @ApiOperation(value="测试post")
    @ApiResponses({
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name="jsonParams",value="json",paramType="body")
    })
    @PostMapping("/api/posttest")
    public RestMessage postTest(
            @RequestBody JSONObject jsonParams
    ){
        RestMessage restMessage = new RestMessage();
        restMessage.setCode(HttpStatus.HTTP_OK);
        restMessage.setData(jsonParams);
        restMessage.setMessage("返回成功!");
        restMessage.setSuccess(true);
        return restMessage;
    }
}
  • @Api:"用在Conntroller类上,表示对类的说明:

    1. tags= 说明该类的作用,可以在UI界面上看到配置的内容。
    2. value= 在UI界面上看不到到,可不配置。
  • @ApiOperation:用在Conntroller类的方法上,说明方法的用途、作用:

    1. value= 说明方法的用途、作用。
    2. notes= 方法的备注说明。
  • @ApiImplicitParams: 用在Conntroller类的方法上,表示一组参数说明:

    • @ApiImplicitParam: 用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
      1. name: 参数名称。
      2. value: 参数的汉字说明、解释。
      3. required: 参数是否必须项。
      4. paramType: 参数放在哪个地方。
        • header:参数在request header获取,@RequestHeader。
        • query:请求参数的获取,@RequestParam。
        • path:以地址的形式提交,@PathVariable。
        • body:请求参数的获取,@RequestBody,仅支持Post。
        • form:以form表单的形式提交 仅支持Post。
      5. dataType:参数类型,默认String,其它值如dataType="Integer"。
      6. defaultValue:参数的默认值。
  • @ ApiResponses: 用在Conntroller类的方法上,表示一组响应:

    • @ ApiResponse: 用在@ApiResponses中,一般用于表达一个错误的响应信息
      1. code: 数字,例如400。
      2. message: 信息内容。
      3. response: 抛出异常的类。
        @ ApiResponses
  • @ ApiModel: 用于响应类上,表示一个返回响应数据的信息:

    • @ ApiModelProperty: 用在属性上,描述响应类的属性。
import cn.hutool.json.JSONObject;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable {

    @ApiModelProperty(value = "是否成功")
    private boolean success;

    @ApiModelProperty(value = "返回对象")
    private JSONObject data;

    @ApiModelProperty(value = "状态码")
    private Integer code;

    @ApiModelProperty(value = "返回信息")
    private String message;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public JSONObject getData() {
        return data;
    }

    public void setData(JSONObject data) {
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

ok,启动Spring boot,输入http://localhost:8081/swagger-ui.html

swagger

相关文章

  • Springboot2.3.0集成swagger2.9.2

    一、导入依赖 二、创建swagger配置   在Application.java同级,创建Swagger2的配置类...

  • Swagger2.9.2的NumberFormatExcepti

    问题 环境 SpringCloud、Swagger2.9.2版本,在访问swagger首页的时候,控制台报错。 可...

  • SpringBoot 2.2.5 整合Swagger 2.9.2

    前言:该博客主要是记录自己学习的过程,方便以后查看,当然也希望能够帮到大家。 引Swagger2.9.2,主要用于...

  • 【3】企业集成EAI概要

    企业应用集成(EAI)可以包括表示集成、数据集成、控制集成和业务流程集成等多个层次和方面。 1.表示集成表示集成也...

  • 集成Facebook广告、分享集成笔记

    集成Facebook广告、分享集成笔记 1、集成Facebook广告2、集成Facebook分享 Facebook...

  • iOS原生集成H5+详细流程

    iOS原生集成H5+ 集成方式 独立应用方式集成 Widget方式集成 WebView方式集成 可以打开官方链接:...

  • iOS开发 - SMSSDK(短信验证)

    Mob 的SMS短信验证集成和使用 1.集成##### 集成可以用cocoapods来集成,也可以手动集成,这里就...

  • SpringBoot 集成

    SpringBoot 集成 redis SpringBoot集成mongodb SpringBoot集成Beetl...

  • 竹木纤维集成墙面好不好

    竹木纤维集成墙面优点 集成墙板十大品牌排名竹木纤维集成墙面用户集成墙面价格表 竹木纤维集成墙面 新型集成墙面装饰板...

  • iOS 友盟分享

    前言:学习笔记大致流程: (只记录 pod集成)1.集成SDK 1.1 自动集成 (Pod) [集成链接](...

网友评论

    本文标题:Springboot2.3.0集成swagger2.9.2

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