- 简介
Swagger UI允许任何人—无论是您的开发团队还是您的最终消费者—可视化并与API的资源交互,而不需要任何适当的实现逻辑。它是由您的OpenAPI(以前称为Swagger)规范自动生成的,带有可视化文档,便于后端实现和客户端使用。
这是Swagger官网上对Swagger UI的介绍,简单讲就是它提供了一个可视化的API文档
- 引入依赖
SpringBoot集成的依赖
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
或
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- 创建Swagger配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @author By 尚
* @date 2019/4/2 18:08
*/
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
// 该处可不指定组别,Swagger默认指定了一个名为default的组
.groupName("myGroup")
.apiInfo(apiInfo())
.select()
//这里采用包扫描的方式来确定要显示的接口
.apis(RequestHandlerSelectors.basePackage("cn.hgd11.swagger.success.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Docker Operation Rest Api Doc")
.description("Docker Operation Api文档")
.version("1.0")
.build();
}
}
说明:本例中使用扫描包的形式加载Controller层,Swagger也提供了其它的形式,如扫描配置了某些特定注解了类或是配置某些注解的方法。在使用中扫描包的形式最为常见,本例也采用这样的方法。
- 创建Controller
import cn.hgd11.swagger.success.entity.TestEntity;
import cn.hgd11.swagger.success.entity.TestEntity2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author :尚村山夫
* @date :Created in 2019/9/14 22:54
* @modified By:
*/
@RestController
@RequestMapping("test2")
@Api(tags = "测试2") // 对该Controller进行说明的注解,如"用户管理","部门管理",本例"测试2"
public class Test2Controller {
@GetMapping
@ApiOperation("测试方法1") // 用户对该接口进行说明的注解
public TestEntity testEntity(){
return new TestEntity();
}
@PostMapping
@ApiOperation("测试方法2") // 用户对该接口进行说明的注解
public TestEntity testEntity(TestEntity2 testEntity2){
return new TestEntity();
}
}
在浏览器中访问localhost:8412/swagger-ui.html,即可得到Swagger文档。IP和端口据实际情况而定,访问的页面一定是swagger-ui.html
对于Swagger中如何进行参数说明及如何添加头信息,如添加Authorization认证,请参考https://blog.csdn.net/shangcunshanfu/article/details/100838687Swagger使用介绍二之为Controller中参数添加字段说明