#所需的maven依赖
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
创建一个SwaggerConfig
在类上配置@Configuration和@EnableSwagger2
@EnableSwagger2 用来开启 swagger2
在docket方法配置好后,此时,以可直接运行并访问http://localhost:8081/swagger-ui.htm
@Configuration
@EnableSwagger2 //开启swagger2
public class SwaggerConfig {
//配置swagger的Docketd的Bean实例
@Bean
public Docket docket(Environment environment) {
//设置要显示的Swagger环境
Profiles of = Profiles.of("dev","prod");
//通过environment.acceptsProfles判断是否在自己设定的环境中
boolean flag = environment.acceptsProfiles(of);
System.out.println(flag);
return new Docket(documentationType.SWAGGER_2)
.groupName("小洲")
.apiInfo(apiInfo())
.enable(flag)//enable是否启动Swagger,如果为false,则Swagger不能在留恋其中访问
.select()
//RequestHandlerSelectors 要扫描接口的方式
//basePackage:指定要扫描的包
//any:扫描全部
//none:全部不扫描
//withMethodAnnotation:扫描方法上的注解,参数是一个注解的反射对象
//withClassAnnotation:扫描类上的注解
.apis(RequestHandlerSelectors.basePackage("com.cfz.swagger.controller"))
.build();
//过滤什么路径
//.paths("/cfz/**")
}
Docket
Docket中的.apiInfoDocket方法完成后访问http://localhost:8081/swagger-ui.htm来查看
用来配置swagger页面的主要信息、要扫描的包、以及作者信息等
配置作者信息,其中源码如下
static {
DEFAULT = new ApiInfo("Api documentation", "Api documentation", "1.0", "urn:tos", DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList());
}
这是默认的信息,将其复制在DocketConfig类中,创建一个方法来修改默认的信息,如下:
public ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("小洲", "无了无了", "1095858425@qq.com");
return new ApiInfo(
"小洲的SwaggerAPI文档",
"水能载舟,亦能覆舟",
"1.0",
"urn:tos",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
可以配置多个作者的独立信息与配置
@Bean
public Docket docket1() {
return new Docket(documentationType.SWAGGER_2).groupName("曹师傅");
}
@Bean
public Docket docket2() {
return new Docket(documentationType.SWAGGER_2).groupName("郝师傅");
}
@Bean
public Docket docket3() {
return new Docket(documentationType.SWAGGER_2).groupName("李师傅");
}
设置要显示的Swagger环境
Profiles of = Profiles.of("dev","prod");
//通过environment.acceptsProfles判断是否在自己设定的环境中
boolean flag = environment.acceptsProfiles(of);
然后将 return new Docket(documentationType.SWAGGER_2).enable(flag)
return new Docket(documentationType.SWAGGER_2).enable(flag);
最后启动springboot项目访问http://localhost:8081/swagger-ui.htm



