Swagger的使用
使用Swagger
springboot集成Swagger
使用Swagger需要导入swagger2 和ui
在pom.xml中引入坐标
swagger-ui
<!-- 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>
springfox-swagger2
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
开启Swagger2
在springboot中创建Swagger的配置类
编写配置类
@Configuration
@EnableSwagger2 //开启swagger2
public class SwaggerConfig {
}
启动springboot,访问页面 http://localhost:8080/swagger-ui.html
@RestController
public class HelloController {
@RequestMapping(value = "/hello")
public String hello(){
return "hello";
}
}
配置Swagger信息
//配置了swagger 的docket的bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
//作者信息
Contact DEFAULT_CONTACT = new Contact("馄饨", "http://localhost", "894645250@qq.com");
return new ApiInfo(
"Api 接口文档日志",
"描述:这是个api文档",
"1.0",
"urn:tos",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
配置swagger 的docket的bean实例
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
//RequestHandlerSelectors,配置要扫描接口的方式
//basePackage 指定要扫描的包
//any()扫描全部
//none()不扫描
// withClassAnnotation(final Class<? extends Annotation> annotation):扫描类上的注解
//withMethodAnnotation(final Class<? extends Annotation> annotation);扫描方法上的注解
.apis(RequestHandlerSelectors.withClassAnnotation(GetMapping.class))
//paths 过滤路径
.paths(PathSelectors.ant("/example/**"))
//
.build();
}
配置是否启动Swagger
new Docket(DocumentationType.SWAGGER_2).enable(boolean)
配置API文档的分组
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}
注意点
在正式发布的时候关闭Swagger!!!出于安全考虑,而且节省运行的内存