一、引入swagger依赖包:
<!-- ######################## swagger2 (此三项依赖必须同时引入) start ########################## -->
<!-- swagger2 依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- swagger ui 依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- swagger bootstrap ui 依赖 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<!-- ######################## swagger2 (此三项依赖必须同时引入) end ########################## -->
二、编写swagger配置类:
package com.hkl.configure;
import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/**
* <p>ClassName:SwaggerConfigure</p >
* <p>Description:Swagger2配置类</p >
* <p>Author:</p >
* <p>Date:2021-9-20</p >
*/
@Configuration
@EnableSwagger2
public class SwaggerConfigure {
@Bean
public Docket createRestApi() {
//添加全局参数,如不需要可以取消
ParameterBuilder tokenPar = new ParameterBuilder();
tokenPar.name("Authorization").description("认证token").modelRef(new ModelRef("string")).parameterType("header").required(false).defaultValue("Bearer ").build();
List<Parameter> globalParams = new ArrayList<Parameter>();
globalParams.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) //构建api文档详细信息
.select()
//扫描包路径
//.apis(RequestHandlerSelectors.basePackage("com.siwei.insurance.productManage"))
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) //扫描包含@Api注解的类
.paths(PathSelectors.any()) //对所有路径进行监控
.build()
.globalOperationParameters(globalParams); //设置swagger接口全局参数
}
//构建 api文档的详细信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("demo")
//描述
.description("接口文档")
//创建人
//.contact(new Contact("LinXiuNan", "", ""))
//版本号
.version("1.0")
.build();
}
//隐藏ui上的models信息
@Bean
public UiConfiguration uiConfiguration(){
return UiConfigurationBuilder
.builder()
.defaultModelsExpandDepth(-1) //-1隐藏,默认不隐藏
.build();
}
}
复制直接使用