Swagger3使用
参考连接:https://github.com/springfox/springfox
swagger2,上传文件有bug,不能实现多文件单字段上传,而且封装到对象里面的文件字段也不能上传文件,swagger3修正了该BUG,并且Swagger3.0简化了配置
1 项目中添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2 创建配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.Collections;
import java.util.List;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.select()
.apis(RequestHandlerSelectors.basePackage("com.luke.health"))
.paths(PathSelectors.any())
.build()
.groupName("api")
.apiInfo(createApiInfo())
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo createApiInfo() {
return new ApiInfoBuilder()
.title("智慧健康API服务")
.description("用于智慧健康系统前后端交互,提供一套API说明")
.version("1.0.0")
.contact(new Contact("Luke", "http://www.xxx.com", "xxxx@mail.com"))
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
private List<SecurityScheme> securitySchemes() {
return Collections.singletonList(
new ApiKey("Authorization", "Authorization", "header"));
}
private List<SecurityContext> securityContexts() {
return Collections.singletonList(
SecurityContext.builder()
.securityReferences(defaultAuth())
.build()
);
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Collections.singletonList(new SecurityReference("Authorization", authorizationScopes));
}
}
与Swagger2对比,将@EnableSwagger2
注解换成了@EnableOpenApi
,将DocumentationType.SWAGGER_2
换成DocumentationType.OAS_30
3 注解变化
@ApiParam -> @Parameter
@ApiOperation -> @Operation
@Api -> @Tag
@ApiImplicitParams -> @Parameters
@ApiImplicitParam -> @Parameter
@ApiIgnore -> @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden
@ApiModel -> @Schema
@ApiModelProperty -> @Schema
当然swagger2的注解仍然可以使用
4 访问地址变更
http://localhost:8080/swagger-ui/index.html