Swagger2应用组成
1、配置Maven依赖
<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>
2、Swagger配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
// springfox.documentation.service.Contact
Contact contact = new Contact("团队名", "www.my.com", "my@my.com");
return new ApiInfoBuilder()
.title("文档标题")
.description("文档描述")
.contact(contact) // 联系方式
.version("1.1.0") // 版本
.build();
}
}
3、Spring MVC配置
<bean class="com.hogen.config.SwaggerConfig"></bean>
<mvc:default-servlet-handler/>
<!-- 根据profile配置不同的location,就可以在生产环境中禁用Swagger -->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
4、在Controller中使用Swagger注解
@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";
}
}
5、访问接口文档:localhost:8080/swagger-ui.html
6、swagger-ui.html 中导出的API文件可以在 Swagger Editor(http://editor.swagger.io/) 中打开
7、在Swagger Editor中,Generate Client 可以生成html版的API文档
整合 Spring Security
// 配置权限豁免,才能正常访问 localhost:8080/swagger-ui.html
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/v2/api-docs").permitAll()