本文是为了记录在springboot项目中使用swagger2构建restful api文档,供使用人员查看,测试接口。
重点是使用流程。
前提:
对maven项目有一点了解
能构建一个最基础的helloworld springboot项目
1.在pom.xml文件中配置依赖包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2.创建swagger2的配置类
在HelloWorldController文件的同级位置创建swagger2的配置类文件,取名为swagger2Config,文件内容如下;
相关包自己导入
@Configuration
@EnableSwagger2
public class Swagger2Config {
//访问路径 /swagger-ui.html
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))//根据自己项目修改
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
//访问地址 /swagger-ui.html
return new ApiInfoBuilder()
.title("RESTful APIs ")
.description("Restful API文档")
.version("1.0")
.build();
}
}
3.在HelloWorldController中添加注解
文件内容如下
@RestController
@Api(value = "用户服务信息查询",description = "HelloWorldController信息")
public class HelloWorldController {
@RequestMapping("/api/hello")
@ApiOperation(value = "sayHello信息查询")
public String sayHello(){
return "hello";
}
}
4.启动项目,输入地址http://localhost:8080/swagger-ui.html查看结果
说明:这是一个简单的使用,是为了说明配置好swagger2Config文件之后,在controller里面使用注解就可以生成接口文档。如果想做添加更多的条件,修改更多的内容,就需要扩展这个代码。比如添加验证,扫描那些接口都可以在swagger2Config文件中配置,请查看相关文档。