springboot 整合swagger
依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- 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>
配置
@Configuration
@EnableSwagger2
public class swaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//指定api扫描路径 此处是指定包路径
.apis(RequestHandlerSelectors.basePackage("com.lym.springbootsecuritytest.controller"))
//任意路径
// .apis(RequestHandlerSelectors.any())
//扫描 添加了 @ApiOperation 注解的方法
//.apis(RequestHandlerSelectors.withClassAnnotation(ApiOperation.class))
//不进行路径过滤
.paths(PathSelectors.any())
.build();
// return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("Spring Boot 使用 Swagger2 构建RESTful API")
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
配置扫描路径
any() // 扫描所有,项目中的所有接口都会被扫描到
none() // 不扫描接口
// 通过方法上的注解扫描,如withMethodAnnotation(GetMapping.class)只扫描get请求
withMethodAnnotation(final Class<? extends Annotation> annotation)
// 通过类上的注解扫描,如.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口
withClassAnnotation(final Class<? extends Annotation> annotation)
basePackage(final String basePackage) // 根据包路径扫描接口
过滤静态资源
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
.apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
// 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
.paths(PathSelectors.ant("/kuang/**"))
.build();
}
接扫描包路径的相关方法
any() // 任何请求都扫描
none() // 任何请求都不扫描
regex(final String pathRegex) // 通过正则表达式控制
ant(final String antPattern) // 通过ant()控制
常用注解
@Api:作用在类上,对类的一个描述,一般放在controller上作为一类接口的说明
@ApiOperation:作用在单个接口方法上,作为单个接口的说明
@ApiParam:作用在接口参数上,作为接口入参的说明
@ApiModelProperty:作用在对象属性上,作为属性的说明