学习课程名称:Swagger接口文档神器
章节名称:Swagger扩展
讲师:晴天哥
课程内容:
- Swagger权限管控
- Swagger多环境控制
引入swagger和swagger-ui的maven依赖
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<!-- swagger2 ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
启动类上加上启用swagger2的注解:@EnableSwagger2
编写swagger2的配置类
import org.springframework.beans.factory.annotation.Value;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class Swagger2Config {
//动态配置多环境是否开启
@Value("${swagger2.enable}")
private boolean swagger2Enable;
/**
* Docket类:一个用于作为进入swagger-springmvc框架的主要接口的构建器。提供合理的默认设置和方便的配置方法
* @return
*/
@Bean
public Docket createApiDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swagger2Enable)//动态配置是否开启swagger,生产环境设置为false
.groupName("延庆版本")//设置栏目名称,如果包含多个栏目,只需要将该生成Docket的方法复制多份,修改方法名和gropname的名称(不支持多个Docket用同样的groupName)和即可
.pathMapping("/")//设置api根路径
.apiInfo(apiInfo())//也可以不通过方法直接在参数中new出来
.select()//启动用于api选择的构造器。返回api选择生成器。要完成api选择器的构建,需要调用api选择器的构建方法,这将在调用build()方法时自动返回到构建docket
.apis(RequestHandlerSelectors.basePackage("com.cloudplatform.hjy.controller"))// controller路径
.paths(PathSelectors.any())
.build();
}
@Bean
public Docket createApiDocketSpare() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swagger2Enable)
.groupName("备用栏目")
.pathMapping("/")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.cloudplatform.hjy.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("平台接口文档")
.description("API文档描述").contact(new Contact("fans"))
.version("0.0.1").build();
}
}