简体   繁体   中英

Swagger and Spring MVC integration

when integrate swagger with mvc and use java-based configuration like

@Configuration
@EnableSwagger2
@PropertySource("classpath:application.properties")
public class SwaggerConfig extends WebMvcConfigurerAdapter {
    .
    .
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

and use url http://localhost:8080/admin-api/admin/swagger-ui.html it give 404. when i remove addResourceHandlers from SwaggerConfig configuration class and configure through xml like

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />

with the same url http://localhost:8080/admin-api/admin/swagger-ui.html it run without problems. how can i use java-based configuration?

In swagger - java based configuration a class exteds from WebMvcConfigurerAdapter, in that class file by override addResourceHandlers like below

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

Try flagging your SwaggerConfig with @EnableWebMvc and register "**/**" as another ResourceHandler, as follows:

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

Also have a look at Docket , here is the link for the sample application using Docket API- swagger-example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM