swagger的使用
1、导入依赖
<!-- swagger依赖-->
<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>
<!-- spring-security 安全验证框架,swagger集成 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- knife4j swagger美化框架-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
2、配置文件配置
# 应用服务 WEB 访问端口
server:
port: 8080
spring:
security:
basic:
# 设置基本认证的路径 , 默认swagger-ui.html
path: /doc.html
# 是否启用基本认证
enabled: true
user:
# 用户名
name: admin
# 密码
password: 123456
3、编写swagger配置类
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.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2 // 开启 Swagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.swagger.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.globalOperationParameters(globalOperationParameters());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API 文档")
.description("这是一个 Swagger API 文档示例")
.version("1.0.0")
.build();
}
private List<Parameter> globalOperationParameters(){
//添加head参数配置start
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
/*配置请求头*/
tokenPar.name("Authorization").description("token令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return pars;
}
}
4、访问
原生访问:http://localhost:8080/swagger-ui.html
美化版本访问:http://localhost:8080/doc.html
标签:swagger,spring,documentation,使用,new,import,springfox From: https://www.cnblogs.com/chuanghongmeng/p/17994955