整合springfox v2

返回目录

1. 配置swagger2所需依赖

<dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>${swagger2.version}</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>${swagger2.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${guava.version}</version>
    </dependency>

2. 启用swagger并进行相关配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(true)   //启用
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.github.zq84.demo"))// 配置监控的起始路径
                .paths(Predicates.not(PathSelectors.regex("/error.*"))) // 错误路径不监控
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("title名称") // 页面标题
                .description("对应的相关描述") // 描述
                .termsOfServiceUrl("")
                // 创建人
                .contact(new Contact("zq84", "https://zq84.github.com", "work_seven@163.com"))
                .version("1.0.0") // 版本
                .build();
    }
}

3. 在Web Controller中使用swagger相关注解配置

下面方法中包括get/post方法请求,其中POST方法中又包含参数为普通对象和Map两种情况
注意:下面代码中参数为Map时只支持前端Form post请求的请求,当前端请求为application/json格式时,不支持

@RestController("swaggerController")
@RequestMapping("/hello")
@Api(tags = "swagger 操作demo")
public class SwaggerController {

    @GetMapping("/{name}")
    @ApiOperation("swagger GET方法")
    public String hello(
            @ApiParam(value = "姓名", example = "Tony")
            @PathVariable("name") String name) {
        return "hello world " + name;
    }
    
    @PostMapping("/user")
    @ApiOperation("post方法,并且参数为普通对象")
    public UserDTO hello(UserDTO user) {
        return user;
    }

    @PostMapping("/mapForm")
    @ApiOperation(value = "form提交post方法,并且参数为普通对象", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", dataTypeClass = String.class, example = "张三", paramType =
                    "query"),
            @ApiImplicitParam(name = "age", value = "年龄", dataType = "int", example = "18", paramType =
                    "query")
    })
    public Map<String, Object> mapForm(@RequestParam @ApiIgnore Map<String, Object> params) {
        params.put("ret", "请求处理为form post");
        return params;
    }
}

4. 页面显示结果

请求地址:http://127.0.0.1:8080/demo/swagger-ui.html

在这里插入图片描述

源码地址:https://gitee.com/johnny/learn-demo/tree/master/springboot-demo/boot02-01-swagger2

©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:上身试试 返回首页