Spring Boot 整合 Swagger2

293 阅读1分钟

使用Swagger2 3.0版本

Swagger2 3.0版本较之前有例如访问地址的变化

配置

  1. 使用 starter 添加相关依赖
<!-- swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
  1. 启动类添加注解
@EnableOpenApi
  1. Swagger配置类
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()                
                .apis(RequestHandlerSelectors.
                 basePackage("xxx.xxx.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("xxx 接口文档")
                        .description("xxx")
                        .version("1.0")
                        .contact(new Contact("kinglyq", "https://www.funsite.top", 
                         "xxx@xx.com"))
                        // .license("The Apache License")
                        // .licenseUrl("http://www.baidu.com")
                        .build());
    }
}
  1. 访问地址
${baseurl}/swagger-ui/index.html

使用

访问接口的排除

  • 比如在spring security中
// 排除的接口
String[] permits = {
        // swagger相关
        "/swagger-ui/*",
        "/swagger-resources/**",
        "/v2/api-docs",
        "/v3/api-docs",
        "/webjars/**"
};
.antMatchers(permits).permitAll()