java +swagger3项目配置
1.添加依赖
<!-- swagger3 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
2.swagger配置文件
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; 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.service.contexts.SecurityContext; import org.springframework.context.annotation.Bean; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import java.util.ArrayList; import java.util.Collections; import java.util.List; @Configuration @EnableOpenApi public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket docket() { return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() // 自行修改为自己的接口路径,不配置扫描全部路径 .apis(RequestHandlerSelectors.basePackage("com.example.mybatisplus_test01.controller")) .paths(PathSelectors.any()) .build()//; .securitySchemes(securitySchemes()) .securityContexts(Collections.singletonList(securityContext())); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger3 API文档") .description("RESTFul 风格接口") .version("1.0") .build(); } private List<SecurityScheme> securitySchemes() { List<SecurityScheme> apiKeyList= new ArrayList<>(); //注意,这里应对应登录token鉴权对应的k-v apiKeyList.add(new ApiKey("Authorization", "Authorization", "header")); return apiKeyList; } /** * 这里设置 swagger2 认证的安全上下文 */ private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(Collections.singletonList(new SecurityReference("Authorization", scopes()))) .build(); } /** * 这里是写允许认证的scope */ private AuthorizationScope[] scopes() { return new AuthorizationScope[]{ new AuthorizationScope("web", "All scope is trusted!") }; } }
效果:
注意:
访问不到swagger时,自定义路径