添加相关依赖
<!-- springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
编写配置类
@EnableSwagger2 //开启Swagger2的支持
@Configuration
public class SwaggerConfig {
/**
* 在spring容器配置一个bean对象
* @Bean等价于 <bean id="createRestApi" class="xxxx.Docket">
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//扫描有ApiOperation注解的方法
.paths(PathSelectors.any())
.build();
}
/**
* 创建api的基本信息
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("集成Swagger2构建RESTful APIs")
.description("集成Swagger2构建RESTful APIs")
.termsOfServiceUrl("自定义")
.contact(new Contact("自定义","自定义","自定义"))
.license("采用 Apache 2.0 开源许可证")
.licenseUrl("自定义")
.version("1.0.0")
.build();
}
}
使用,直接在代码上使用
@Api("springboot使用swagger测试")
@RestController
public class SwaggerController {
@ApiOperation(value = "获取用户信息", notes = "根据id来获取用户详细信息")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", dataType = "Integer"),
@ApiImplicitParam(paramType = "path", name = "status", value = "用户状态", dataType = "Integer"),
})
@ApiResponses({
@ApiResponse(code = 400, message = "缺少必要的请求参数"),
@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
})
@RequestMapping(value = "/swagger/{id}/{status}",method = RequestMethod.GET)
public Users getUserInfo(@PathVariable("id") Integer id, @PathVariable("status") Integer status) {
Users users = new Users();
users.setId(id);
users.setNick("cat");
users.setPhone("1370000000");
users.setPassword("******");
users.setEmail("cat@163.com");
users.setAccount("NO68958886878664");
return users;
}
}
说明
还有@ApiModel和@ApiModelProperty用于描述某个模型及其属性
原文:https://www.cnblogs.com/zhaojunjin/p/14965591.html