- 创建spring boot工程
- 导入依赖
springfox-swagger2 && springfox-swagger-ui
- 准备配置类
/**
- @author hy
- @date 2018/10/07
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// rest controller package
.apis(RequestHandlerSelectors.basePackage(“com.xxx.controller”))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(“Spring Boot中使用Swagger2构建RESTful APIs”)
.description(“swagger2入门教程,更多请关注http:https://me.csdn.net/sx_huangying”)
.termsOfServiceUrl(“http:https://me.csdn.net/sx_huangying”)
.contact(“huangy”)
.version(“1.0”)
.build();
}
}
通过@Configuration注解,表明它是一个配置类,@EnableSwagger2开启Swagger2。apiInfo()配置一些基
本的信息。apis()指定扫描的包会生成文档。
- 启动Spring Boot工程运行测试
打开浏览器,输入:http://localhost:8080/v2/api-docs
通过Swagger-UI,浏览器输入:http://localhost:8080/swagger-ui.html
三、生成Swagger2文档的注解
Swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiImplicitParam:一个请求参数
@ApiImplicitParams多个请求参数
四、示例
package com.baizhi.controller;
import com.baizhi.entity.User;
import io.swagger.annotations.;
import org.springframework.web.bind.annotation.;
/**
- @author huangy
- @date 2018/10/07
*/
@Api(value = “swagger controller”,tags = “swagger操作接口”)
@RestController
@RequestMapping("/swagger")
public class HelloSwaggerController {
@ApiOperation(value = “根据用户名 获取欢迎语”,notes = “注意事项”)
@GetMapping("/sayHello")
public String sayHello(@ApiParam(name=“name”,value = “用户名”,required = true)
@RequestParam(required = true)
String name){
return "Hello: "+name;
}
//@ApiIgnore
@ApiOperation(value = “新增用户信息”)
@PostMapping("/add")
public String addUser(@RequestBody @ApiParam(name=“user”,value=“用户对象”,required =
true) User user){
System.out.println(user);
return “OK”;
}
@ApiOperation(value = “根据年龄和姓名查询用户信息”)
@ApiImplicitParams({
@ApiImplicitParam(name=“userAge”,value = “用户年龄”,required =
true,dataTypeClass = Integer.class,paramType = “query”),
@ApiImplicitParam(name=“name”,value=“用户姓名”,dataType = “string”,paramType
= “query”)
})
@GetMapping("/select")
@ApiResponses({
@ApiResponse(code = 404,message = “没有找到资源”),
@ApiResponse(code = 401,message = “权限不够”)
})
public String selectUser(@RequestParam(“userAge”) Integer age,String name){
return age + " | "+name;
}
}