Spring Boot引入swagger-ui 后swagger-ui.html無法訪問404


最近給graphserver增加swagger,記錄下過程與問題解決。

Swagger 是一個規范和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務,后端集成下Swagger,然后就可以提供一個在線文檔地址給前端同學。

引入 Swagger

pom中加入相關配置:

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

增加Swagger2Config, 添加@EnableSwagger2,可以通過定義Docket bean實現自定義。

@Configuration
@EnableSwagger2
@Profile("swagger")
@ComponentScan("xxx.controller")
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .enable(true)
            .select()
            .apis(RequestHandlerSelectors.basePackage("xxx.controller"))
            .paths(PathSelectors.any())
            .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("XXX Rest Server")
            .description("XXXRest接口")
            .contact(new Contact("contract", "url", "email"))
            .version("1.0")
            .build();
    }
}

swagger-ui.html 404問題

項目中有web配置,因此懷疑是這些配置影響了,搜索下發現這位仁兄有類似經歷:https://www.cnblogs.com/pangguoming/p/10551895.html

於是在WebMvcConfig 配置中,override addResourceHandlers


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

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

搞定收工。

延伸閱讀

server端有了swagger,前端如何更優先的調用?

參見:Vue 使用typescript, 優雅的調用swagger API,筆者提供了一個開源npm庫,可以為前端生成調用axios調用代碼。

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM