本章介绍 SpringBoot1.5 集成 Swagger2 生成在线的API接口文档。
个人学习总结:
链接:【springboot、springcloud、docker 等,学习目录】
1、pom依赖:
io.springfox
springfox-swagger2
2.2.2
io.springfox
springfox-swagger-ui
2.2.2
2、Swagger2Config配置类:
/**
* @Description: swagger2配置类
*/
@Configuration
// 开启swagger2
@EnableSwagger2
// 选择不同的环境启用 swagger 以下两种方式,推荐第一种
//@Profile({"dev","test"})
//@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.coolron"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("更多Spring Boot相关文章请关注:.......")
.termsOfServiceUrl("http://blog.coolron.com/")
.contact("A罗恩和Java")
.version("1.0")
.build();
}
}
3、改造UserController类:
@Slf4j
@Api(description = "用户接口")
@RestController
@RequestMapping(value = "user")
public class UserController {
@Autowired
private UserService userService;
@ApiOperation(value="获取用户列表", notes="")
@RequestMapping(value={"getUserList"}, method= RequestMethod.GET)
public ApiResult getUserList() {
List userList = userService.getAllUser();
return ApiResult.ok(userList);
}
@ApiOperation(value="创建用户", notes="根据User对象创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@RequestMapping(value="saveUser", method=RequestMethod.POST)
public ApiResult saveUser(@RequestBody User user) {
int result = userService.saveUser(user);
return ApiResult.ok(result);
}
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "getUser", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value="getUser/{id}", method=RequestMethod.GET)
public ApiResult getUser(@PathVariable Integer id) {
User user = userService.getUser(id);
return ApiResult.ok(user);
}
@ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
})
@RequestMapping(value="updateUser/{id}", method=RequestMethod.PUT)
public ApiResult putUser(@PathVariable Integer id, @RequestBody User user) {
int result = userService.updateUser(user);
return ApiResult.ok(result);
}
@ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value="delete/{id}", method=RequestMethod.DELETE)
public ApiResult deleteUser(@PathVariable Integer id) {
int result = userService.deleteUser(id);
return ApiResult.ok(result);
}
}
4、测试:访问http://localhost:8080/swagger-ui.html
注意: 访问路径有配置工程名的带上工程名,避免404。此处未配置工程名。
5、使用:GET、POST、PUTD、DELETE等请求方式都可以在此测试,输入必要的参数点击“try it out”按钮即可。