为spring boot 写的Controller中的rest接口配置swagger

1.pom.xml文件中加入下列依赖:

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2.创建一个Swagger2类:
//对swagger的配置
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))//扫描接口的包
.paths(PathSelectors.regex("/rest/.*"))//被文档展示的接口的地址,这里只展示rest/地址下的
.build();
}

public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("spring boot利用swagger构建api文档")
.description("简单优雅的rest风格")
.termsOfServiceUrl("http://www.maycpou.com")//文档遵循的开发协议的展现网址
.version("1.0")//版本
.build();
}
}
3.启动项目后访问http://localhost:8888/swagger-ui.html
4.针对swagger2中还有很多的注解写在接口或者传入传出参数上面,来添加在swagger文档界面增加对该接口或者参数的说明如:
接口方法:
 @ApiOperation(value = "添加文章",notes = "添加新的文章",tags = "Article",httpMethod = "POST")//方法的swagger注释
// @ApiImplicitParams({
// @ApiImplicitParam(name = "id" ,value = "文章Id",required = true,dataType = "String"),
// @ApiImplicitParam(name = "name" ,value = "文章名称",required = true,dataType = "String"),
// })//这个注解是针对请求参数是@RequestParam方式的时候,可以给每个参数添加swagger文档上的注释
@ApiResponses({//方法返回值的swagger注释
@ApiResponse(code = 200,message = "成功",response = AjaxResponse.class),
@ApiResponse(code = 400,message = "用户输入错误",response = AjaxResponse.class),
@ApiResponse(code = 500,message = "系统内部错误",response = AjaxResponse.class)
})
@RequestMapping(value = "/article", method = RequestMethod.POST,produces = "application/json")
//上面的注解等同于@PostMapping("/article")
public AjaxResponse saveArticle(@RequestBody Article article){//使用@RequestBody的方式接收参数,可以自动的将传入的json转化装配为对象
//如果使用@RequestParam的方式接受参数就要将Article对象里面的字段全部写在传入参数中
log.info("saveArticle:{}",article);
return AjaxResponse.success();
}

传出参数:
@Data
@ApiModel//用于swagger的接口返回实体
public class AjaxResponse {
@ApiModelProperty("是否成功")//swagger中显示的返回字段的注释
private boolean isok;
private int code;
private String message;
private Object data;
private AjaxResponse(){

}

public static AjaxResponse success(){
AjaxResponse resultBean = new AjaxResponse();
resultBean.setIsok(true);
resultBean.setCode(200);
resultBean.setMessage("success");
return resultBean;
}

public static AjaxResponse success(Object data){
AjaxResponse resultBean = new AjaxResponse();
resultBean.setIsok(true);
resultBean.setCode(200);
resultBean.setMessage("success");
resultBean.setData(data);
return resultBean;
}
}


猜你喜欢

转载自www.cnblogs.com/maycpou/p/11621807.html