Swagger2 快速定义API接口文档

引入依赖


	io.springfox
	springfox-swagger2
	2.7.0



	io.springfox
	springfox-swagger-ui
	2.7.0

配置

#SWAGGER(一般不需要配置,配置会影响使用,默认/v2/api-docs)
springfox.documentation.swagger.v2.path=/xzh
/**
 * Swagger2配置
 * @author 向振华
 * @date 2018/11/21 11:02
 */
@Configuration
@EnableSwagger2
@Profile({"dev", "test"})//在何环境显示
public class Swagger2 {

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

    /**
     * 构建 api文档的详细信息函数
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("标题API")
                .contact(new Contact("向振华", "网站url", "邮箱地址"))
                .version("1.0.0")
                .build();
    }

}

请求参数定义

/**
 *  请求参数
 * @author 向振华
 * @date 2018/11/21 11:13
 */
@Data
public class Model {

    @ApiModelProperty(value = "名称")
    private String name;
    @ApiModelProperty(value = "客户地区")
    private String area;

}

Controller层

/**
 * @author 向振华
 * @date 2018/11/21 11:04
 */
@Api(tags = "A服务名称")
@RequestMapping("xzh")
@Controller
public class AController {


    @ApiOperation(value = "方法名1", notes = "备注1")
    @ApiImplicitParam(name = "parm", value = "解释", paramType = "query", required = true)
    @PostMapping("/test1")
    @ResponseBody
    public String test1(Long parm) {//单个参数
        return null;
    }

    @ApiOperation(value = "方法名2")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parm", value = "XXid数组", paramType = "query", required = true),
            @ApiImplicitParam(name = "arg", value = "ZZid数组", paramType = "query", required = true)
    })
    @PostMapping("/test2")
    @ResponseBody
    public String test2(Long[] parm, Long[] arg) {//多个参数
        return null;
    }

    @ApiOperation(value = "方法名3")
    @GetMapping("/test3")
    @ResponseBody
    public String test3(Model model) {//实体类,注解写在实体类内
        return null;
    }
}

启动服务器,访问http://localhost:8001/swagger-ui.html#/

进入页面

Swagger2 快速定义API接口文档_第1张图片

点开A服务

Swagger2 快速定义API接口文档_第2张图片

 

 

 

常用注解:

@Api()用于类; 
表示标识这个类是swagger的资源 

@ApiOperation()用于方法; 
表示一个http请求的操作 

@ApiParam()用于方法,参数,字段说明; 
表示对参数的添加元数据(说明或是否必填等) 

@ApiModel()用于类 
表示对类进行说明,用于参数用实体类接收 

@ApiModelProperty()用于方法,字段 
表示对model属性的说明或者数据操作更改 

@ApiIgnore()用于类,方法,方法参数 
表示这个方法或者类被忽略 

@ApiImplicitParam() 用于方法 
表示单独的请求参数 

@ApiImplicitParams() 用于方法,
表示 包含多个 @ApiImplicitParam

 

你可能感兴趣的:(Other)