在springboot项目中想使用swagger2作为接口查看文档:
1. 使用的jar包 :在pom.xml文件中 引入下面的依赖
<!--引入Swagger2的依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
2. 在启动类上面添加下面的注解,此时就可以打开 链接 http://127.0.0.1:8081/swagger-ui.html#/
@EnableSwagger2
3.但是经过前两步骤之后 在swagger页面会出现 BaseController 等不必要信息,则可以在代码中写一个配置类,将其过滤掉:
/**
* 此配置文件:
* 解决访问swaggerUI接口文档显示basic-error-controler问题
* */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.pathMapping("/")
.select() // 选择那些路径和api会生成document
.apis(RequestHandlerSelectors.any())// 对所有api进行监控
//不显示错误的接口地址
.paths(Predicates.not(PathSelectors.regex("/error.*")))//错误路径不监控
.paths(PathSelectors.regex("/.*"))// 对根下所有路径进行监控
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("API接口文档")
.license("The Apache License, Version 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.version("v1.0")
.build();
}
}
经过上面3步之后可以正常使用swagger页面查看接口信息(尽量使用swagger的一些注解及@Api等)
注意⚠️:
项目里面有针对于swagger的特殊需求,将一些必填参数在swagger中展示
方式一:globalOperationParameters参数 --- 全局
@Bean
public Docket customDocket() {
List<Parameter> pars = new ArrayList(2);
pars.add(buildHeader(FilterHeaderEnum.DEBUG));
pars.add(buildHeader(FilterHeaderEnum.TIMESTAMP));
return new Docket(DocumentationType.SWAGGER_2)
//.groupName("权益中心接口")
.select()
.apis(RequestHandlerSelectors.basePackage("com.ke.sun.biz.api"))
.build()
.globalOperationParameters(pars)
.apiInfo(apiInfo());
}
private Parameter buildHeader(FilterHeaderEnum fhe) {
return new ParameterBuilder().name(fhe.getName()).description(fhe.getDesc())
.modelRef(new ModelRef(fhe.getType())).parameterType("header")
.required(false).defaultValue(fhe.getValue()).build();
}
方式二注解:使用@ApiImplicitParams
来额外标注一个请求头参数 --- 接口层面
// 如果需要额外的参数,非本方法用到,但过滤器要用,类似于权限token
@PostMapping("/login6")
@ApiOperation(value = "带token的接口",notes = "带token的接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "authorization",//参数名字
value = "授权token",//参数的描述
required = true,//是否必须传入
paramType = "header"
)
,
@ApiImplicitParam(name = "username",//参数名字
value = "用户名",//参数的描述
required = true,//是否必须传入
paramType = "query"
)
})
public String login6(String username){
return username;
}