SpringBoot使用Swagger2创建API文档
SpringBoot使用Swagger2创建API文档
一、在pom文件中加入以下依赖
<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>
二、在启动类同一目录下创建Swagger2.java
内容如下:
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxxx.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot入门利用swagger构建api文档")
.description("使用restfun风格")
.termsOfServiceUrl("http://www.xxx.cn")
.version("1.0")
.build();
}
}
三、配置API内容
1、在想要创建API的类上加上
@Api(description = "User Controller") 也就是这个类的描述
2、在方法上使用
@ApiOperation(value = "不需要参数返回所有user数据", notes = "不需要参数返回list", httpMethod = "GET")
四、访问API页面
SpringBoot应用成功启动后,访问
http://localhost:8080/swagger-ui.html
就可以看到相应的Controller以及里面的方法。可以点击对应的Try it out 来进行服务的方法,如果有参数的话,可以在Parameters 里面填写参数
