一·流程
1·新建一个SpringBoot项目
2·导入相关依赖
3·编写一个Hello工程
4·配置Swagger==》Config
二·依赖
1·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>
2·Springfox Swagger用户界面
<!-- 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>
3`配置swagger的config
package com.kuang.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2//开启Swagger2
public class SwaggerConfig {
//配置swagger的 docket的bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
//配置Swagger信息 apiInfo
private ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("琴江", "https://blog.youkuaiyun.com/weixin_44423634/article/details/106186130", "110112119");
return new ApiInfo(
"狂小生api文档",
"即使再小的帆也能远航",
"1.0",
"https://blog.youkuaiyun.com/weixin_44423634/article/details/106186130",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<VendorExtension>()
);
}
}
Swagger配置扫描接口
Docket.select()
.select()
//RequestHandlerSelectors,配置要扫描的接口方式
//basePackage指定要扫描的包
//any()全部扫描
//none() 全不扫描
//withClassAnnotation 扫描类上的注解,参数是一个注解的反射对象
//withMethodAnnotation 扫描方法上的注解
.apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
//paths() 过滤什么路径
.paths(PathSelectors.ant("/kuang/**"))
.build();
4·配置是否启动Swagger
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.enable(flag)
.select()
开关,一个判断
比如:我只想我的Swagger在生产环境中使用,在发布的时候不使用
- 判断是不是生产环境flag =false
- 注入enable(flag)
@Bean
public Docket docket(Environment environment){
//设置要显示的swagger环境
Profiles profiles= Profiles.of("dev","test");
//通过environment.acceptsProfiles判断是否处在自己设定的环境中
boolean flag=environment.acceptsProfiles(profiles);
System.out.println(flag);
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.enable(flag)
.select()