基本配置
- 导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
访问swagger ui,http://localhost:8080/swagger-ui/index.html
- 编写配置类,配置基本信息
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
Contact contact= new Contact("kittyguy","https://www.kittyguy.com","yangyanhua@gmail.com");
return new ApiInfoBuilder()//链式编程
.title("非常强的api")
.description("这个api可以赚10个亿")
.termsOfServiceUrl("https://www.baidu.com/")
.license("中国工信部许可2.1")
.contact(contact)
.version("3.0")
.build();
}
}
配置要扫描的接口
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
/*
select()启动用于api选择的构建器。
返回值: api选择生成器。要完成api选择器的构建,需要调用api选择器的build方法,当调用build方法时,它将自动回退到
构建摘要。
*/
// RequestHandlerselectors.配置要扫描接口的方式
// basePackage:指定要扫描的包
// any():扫描全部
// none():不扫描
//withclassAnnotation:扫描类上的注解,参数是一个注解的反射对象
// withMethodAnnotation:扫描方法上的注解
.apis(RequestHandlerSelectors.basePackage("com.boot.controller"))//扫描的接口,以包为准
.paths(PathSelectors.ant("/hello"))//规定什么样的url请求会被扫描
.build();
}
}
在开发环境中使用swagger,在使用环境不使用
- 3个配置文件 application.properties
spring.profiles.active=dev
#激活的配置文件
application-dev.properties
server.port=8082
application-prod.properties
server.port=8081
- 配置类
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket docket(Environment environment){
Profiles profiles = Profiles.of("prod","test");
boolean isOnActive = environment.acceptsProfiles(profiles);//判断所属环境,即对应文件是否激活
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(isOnActive)//是否启用swagger
.select()
/*
select()启动用于api选择的构建器。
返回值: api选择生成器。要完成api选择器的构建,需要调用api选择器的build方法,当调用build方法时,它将自动回退到
构建摘要。
*/
// RequestHandlerselectors.配置要扫描接口的方式
// basePackage:指定要扫描的包
// any():扫描全部
// none():不扫描
//withclassAnnotation:扫描类上的注解,参数是一个注解的反射对象
// withMethodAnnotation:扫描方法上的注解
.apis(RequestHandlerSelectors.basePackage("com.boot.controller"))//扫描的接口,以包为准
.paths(PathSelectors.ant("/hello"))//规定什么样的url请求会被扫描
.build();
}
}