如何在为swagger服务描述呈现路径时考虑servlet路径映射

时间:2015-05-04 18:53:35

标签: java spring-mvc java-ee swagger swagger-ui

我在配置swagger时遇到问题。当我在web.xml中为servlet指定链接时,如

<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

swagger显示url-s没有... / rest / ...所以我不能使用swagger-ui进行测试,当我指定url-pattern / * swagger-ui不起作用时。这是配置类

@Configuration
@EnableSwagger
public class DocumentationController extends WebMvcConfigurerAdapter {
    private SpringSwaggerConfig springSwaggerConfig;
    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
        this.springSwaggerConfig = springSwaggerConfig;
    }
    @Bean
    public SwaggerSpringMvcPlugin customImplementation() {
        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(
                apiInfo())
                .genericModelSubstitutes(ResponseEntity.class)
                .includePatterns("/.*");
    }
    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo("1-st Project's REST API",
                "Write a description of REST API.",
                "link",
                "mail",
                "API License",
                "link");
        return apiInfo;
    }

}

1 个答案:

答案 0 :(得分:2)

您似乎正在使用pre 2.0.0版本的springfox。

解决方案有点棘手,并没有真正经过测试,因此无法保证这项工作,但值得一试。

//NOTE: The following code is only an outline to highlight relevant code snippets
@Bean 
public SwaggerSpringMvcPlugin plugin() {
    new SwaggerSpringMvcPlugin(...)
        //more config
        .pathProvider(yourPathProvider());
}

private SwaggerPathProvider yourPathProvider() {
    SwaggerPathProvider pathProvider = new RelativeSwaggerPathProvider(...);
    pathProvider.setApiResourcePrefix("/rest"); //<-- NOTE: this is what you need
    return pathProvider;
}    

如果你搬到2.x,现在会容易得多。甚至有一个document描述了如何从1.x迁移到2.x.

@Bean 
public Docket plugin() {
    new Docket()
        //more config
        .pathMapping("/rest");

}

另请注意,没有针对1.x的计划更新。所以移动到2.0.0的库是一个好主意。