Issue with Static resources when extending Spring

2019-07-04 16:05发布

问题:

I extended WebMvcConfigurationSupport to implement an api versioning scheme - i.e.

@Configuration
public class ApiVersionConfiguration extends WebMvcConfigurationSupport {

    @Override
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        return new ApiVersionRequestMappingHandlerMapping(readDateToVersionMap());
    }}

This uses a custom handler mapping to version the api and works quite nicely.

However it also seems to disable the @EnableAutoConfiguration bean so that now static resources aren't served (as mentioned in this question Is it possible to extend WebMvcConfigurationSupport and use WebMvcAutoConfiguration?).

Ok, I thought, let's just add a resource handler to the class above - i.e.

@Configuration
public class ApiVersionConfiguration extends WebMvcConfigurationSupport {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("classpath:/public/").addResourceLocations("/");
    }

    @Override
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        return new ApiVersionRequestMappingHandlerMapping(readDateToVersionMap());
    }}

However.. this isn't working..? I get this error when I browse to /index.html:

No mapping found for HTTP request with URI [/index.html] in DispatcherServlet with name 'dispatcherServlet' 

..If I disable this class then these resources are served just fine by @EnableAutoConfiguration magic.

I've been playing with various options to serve static content having extended the WebMvcConfigurationSupport and thus far no success.

Any ideas?

回答1:

I was facing the same problem and came up with a solution that just works for me. If you just want to get the resources working without worrying of repetition you can do:

@Configuration
public class StaticResourcesConfig extends WebMvcAutoConfigurationAdapter {

}

and then

@Configuration
@EnableWebMvc
@Import(StaticResourcesConfig.class)
public class WebConfig extends WebMvcConfigurationSupport {
    ...
}

This successfully uses the Spring Boot defaults for serving static resources, as long as you don't map /** in your controllers.