Swagger2与Knife4j集成(防踩坑)

发布时间 2023-10-04 16:54:52作者: 沈自在。

Swagger2与Knife4j

1 集成Springboot

1.1 依赖

       <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
       <dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-swagger2</artifactId>
           <version>2.9.2</version>
       </dependency>

       <dependency>
           <groupId>com.github.xiaoymin</groupId>
           <artifactId>knife4j-spring-boot-starter</artifactId>
           <!--在引用时请在maven中央仓库搜索2.X最新版本号-->
           <version>2.0.9</version>
       </dependency>

1.2 放开SpringSecurity资源管控

// 在SpringSecurity 中编写
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/**",
                "/swagger-resources/**",
                "/swagger/**",
                "/webjars/**",
                "/swagger-ui.html"
                ).antMatchers(
                        // knife4j 相关
                "/doc.html",
                    "/v2/api-docs-ext/**"
                );
    }

1.3 配置 swagger knife4j 访问静态资源路径

@Configuration
public class SwaggerWebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

1.4 Swagger相关配置

@EnableSwagger2
@Configuration
@EnableKnife4j
@Profile({"dev"})
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }


    private ApiInfo apiInfo(){
        Contact contact = new Contact("沈自在。","https://www.tfirst.top","1315077391@qq.com");
        return new ApiInfo("Api Documentation",
                "药品管理系统",
                "1.0",
                "https://www.tfirst.top",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());

    }