swagger用处

swagger引入坐标

swagger编写配置类

swagger注解引入Controller类(类与方法)

swagger注解引入Controller类(非实体请求参数)

swagger注解引入Controller类(实体请求参数)

swagger注解引入实体类

swagger自定义启用

swagger自定义分组

swagger注解

swagger用处

swagger用于自动生成接口文档,API始终保持同步,脱离PostMan测试接口。正式发布时需关闭swagger,出于安全考虑且节省运行的内存。

访问路径: http://localhost:8080/swagger-ui.html

swagger引入坐标

springboot集成swagger需要引入以下两个包

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

swagger编写配置类

用于开启swagger功能,以及设置 API 文档的基本信息和请求接口的过滤条件。

@Configuration
//开启swagger功能
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                //用于定义API主界面的信息
                .apiInfo(apiInfo())
                //用于控制接口被swagger做成文档
                .select()
                //要扫描的API(Controller)基础包
                .apis(RequestHandlerSelectors.any())
                //扫描路径选择
                .paths(PathSelectors.any())
                .build();

    }

    /**
     * 用于定义API主界面的信息
     * @return
     */
    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()
                //文档标题
                .title("自定义标题")
                //接口概述
                .description("自定义描述")
                //联系人的信息
                .contact(new Contact("联系人名称","www.ferao.com","ferao@qq.com"))
                //版本号
                .version("1.0")
                //定义服务的域名
                .termsOfServiceUrl(String.format("url"))
                //.license("LICENSE")//证书
                //.licenseUrl("http://www.guangxu.com")//证书的url
                .build();
    }

}

项目启动后,可看到项目内可调用的所有接口(无任何描述信息)

在这里插入图片描述

swagger注解引入Controller类

@RestController
@RequestMapping(value = "mode")
@Api(value = "自定义Controller", tags = "Controller标签", description = "Controller描述")
public class FeraoController {

    /**
     * @param demoParam
     * @throws IOException
     * @throws InterruptedException
     */
    @ApiOperation(value = "测试接口", notes = "测试接口注释")
    @GetMapping(value = "demoHander")
    public void demoHander(String demoParam) {

      System.out.println(demoParam);
    }
}

在这里插入图片描述

swagger注解引入Controller类(非实体请求参数)

swagger注解引入Controller类(实体请求参数)

swagger注解引入实体类

1. 只要接口中返回值存在实体类,就会被swagger扫描
2. swagger页面给实体类Moel加注释

@Data
@ApiModel(value="测试实体",description="测试实体描述")
public class DemoFormatInfo {

    @ApiModelProperty(value = "用户名",required = true,example = "root")
    private String dateMode;

    @ApiModelProperty(value = "密码",required = false,example = "123456")
    private String datePassWord;

}

在这里插入图片描述

swagger自定义启用

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${common.swagger.enable}")
    private boolean swaggerEnable;

    @Value("${common.swagger.title}")
    private String title;

    @Value("${common.swagger.description}")
    private String description;

    @Value("${common.swagger.author}")
    private String author;

    @Value("${common.swagger.url}")
    private String url;

    @Value("${common.swagger.mail}")
    private String mail;

    @Value("${common.swagger.version}")
    private String version;

    @Bean
    public Docket api() {

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerEnable)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();

    }

    /**
     * 用于定义API主界面的信息
     * @return
     */
    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .contact(new Contact(author,url,mail))
                .version(version)
                .termsOfServiceUrl(String.format("url"))
                //.license("LICENSE")//证书
                //.licenseUrl("http://www.guangxu.com")//证书的url
                .build();
    }

}
common:
  swagger:
    enable: true
    title: "PERSONAL MODULE"
    description: "A project based on hobbies"
    author: "ferao"
    url: "www.ferao.com"
    mail: "ferao@qq.com"
    version: "1.0"

swagger自定义分组

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${common.swagger.enable}")
    private boolean swaggerEnable;

    @Value("${common.swagger.title}")
    private String title;

    @Value("${common.swagger.description}")
    private String description;

    @Value("${common.swagger.author}")
    private String author;

    @Value("${common.swagger.url}")
    private String url;

    @Value("${common.swagger.mail}")
    private String mail;

    @Value("${common.swagger.version}")
    private String version;

    @Bean
    public Docket api1() {

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerEnable)
                .groupName("ModelOne")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();

    }

    @Bean
    public Docket api2() {

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerEnable)
                .groupName("ModelTWO")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();

    }

    /**
     * 用于定义API主界面的信息
     * @return
     */
    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .contact(new Contact(author,url,mail))
                .version(version)
                .termsOfServiceUrl(String.format("url"))
                //.license("LICENSE")//证书
                //.licenseUrl("http://www.guangxu.com")//证书的url
                .build();
    }

}

在这里插入图片描述

swagger注解

注解作用位置 示例
@EnableSwagger2启用 Swagger 功能
@Api修饰整个类,描述Controller的作用 @Api(value = “app端用户登录”, tags = “ap_user”, description = “app端用户登录API”)
@ApiOperation描述Controller中的接口 @ApiOperation(“用户登录”)
@ApiParam单个参数的描述信息
@ApiModel用对象来接收参数
@ApiModelProperty用对象接收参数时,描述对象的一个字段 @ApiModelProperty(value = “手机号”,required = true) private String phone;
@ApiResponseHTTP响应其中1个描述
@ApiResponsesHTTP响应整体描述
@ApiIgnore使用该注解忽略这个API
@ApiError发生错误返回的信息
@ApiImplicitParam一个请求参数
@ApiImplicitParams多个请求参数的描述信息

进阶配置:扫描接口

@Bean
public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //是否启动swagger 如果是false则不能在浏览器中使用
                .enable(true)
                .select()
                //RequestHandlerSelectors. 配置要扫描的方式
                //basePackage():指定要扫描的包
                //any():扫描全部
                //none():不扫描
                //withClassAnnotation():扫描类上的注解,参数是一个注解的反射对象
                //withMethodAnnotation():扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.ferao.controller"))
                //.paths() .过滤URL
                //any() 任何请求都扫描
                //none() 任何请求都不扫描
                //ant()	通过ant控制
                //regex() 通过正则表达式控制
                .paths(PathSelectors.ant("/ferao/**"))
                .build();
 }

请求接口名称描述

@ApiOperation(value = "1.根据全局变量获得author")
	   @GetMapping("/user")
	   public String getUsers(ModelMap modelMap){
	       System.out.println(modelMap.get("author"));
	       return "User-Messege";
	   }

效果图示例
在这里插入图片描述

请求接口参数描述

@ApiOperation(value = "1.根据全局变量获得author")
@ApiImplicitParams({
        @ApiImplicitParam(name = "name", value = "名称", required = true, paramType = "query", dataType = "String")
})
@GetMapping("/user")
public String getUsers(String name){
    return "User-Messege";
}

效果图示例

在这里插入图片描述

Responses返回类型描述

@ApiOperation(value = "1.根据全局变量获得author") 
@ApiImplicitParams({
     @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = true, paramType = "query", dataType = "String")
    })
})
@ApiResponses({
        @ApiResponse(code=200,message="请求成功"),
        @ApiResponse(code=500,message="系统异常")
})
@GetMapping("/user")
public String getUsers(String name){
    return "User-Messege";
}

[注]
paramType=“body” 代表参数应该放在请求的什么地方:
header–>放在请求头。请求参数的获取:@RequestHeader(代码中接收注解)
query–>用于get请求的参数拼接。请求参数的获取:@RequestParam(代码中接收注解)
path(用于restful接口)–>请求参数的获取:@PathVariable(代码中接收注解)
body–>放在请求体。请求参数的获取:@RequestBody(代码中接收注解)
form(不常用)
dataType=“int” 代表请求参数类型为int类型,当然也可以是Map、User、String等;

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐