swagger2
1、pom.xml 添加 Maven 依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
2、创建 Swagger2Configuration.java
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
//api接口包扫描路径
public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.hzdtech.order.server";
public static final String VERSION = "1.0.0";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
.paths(PathSelectors.any())// 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("订单微服务") //设置文档的标题
.description("单词计数服务 API 接口文档") // 设置文档的描述
.version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information
.termsOfServiceUrl("http://shanpai.video") // 设置文档的License信息->1.3 License information
.build();
}
}
3、API 接口编写
@RestController
@Api(tags="接口所在的类")
@RequestMapping ("/my")
public class MyController {
@RequestMapping(value="/list", method=RequestMethod.POST)
@ApiOperation(value = "接口名", notes = "接口描述", httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "length",value = "参数1", required = true, paramType = "path"),
@ApiImplicitParam(name = "size",value = "参数2", required = true, paramType = "query"),
@ApiImplicitParam(name = "page",value = "参数3", required = true, paramType = "header"),
@ApiImplicitParam(name = "total",value = "参数4", required = true, paramType = "form"),
@ApiImplicitParam(name = "start",value = "参数5",dataType = "string", paramType = "body")
})
public String register(){
return "has permission";
}
}
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:描述一个请求参数,可以配置参数的中文含义,还可以给参数设置默认值
@ApiImplicitParams:描述由多个 @ApiImplicitParam 注解的参数组成的请求参数列表
4、启动 SpringBoot 应用
SpringBoot 启动成功后,访问 http://localhost:8080/swagger-ui.html
###5 5、在 Security 中的配置
Spring Boot 项目中如果集成了 Spring Security,在不做额外配置的情况下,Swagger2 文档会被拦截。解决方法是在 Security 的配置类中重写 configure 方法添加白名单即可:
@Override
public void configure ( WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/swagger-ui.html")
.antMatchers("/v2/**")
.antMatchers("/swagger-resources/**");
}