Spring 5 - How to provide static resources

2019-04-07 08:49发布

I am trying provide static resources in my web application and I tried:

@SuppressWarnings("deprecation")
@Bean
WebMvcConfigurerAdapter configurer(){
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addResourceHandlers (ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/**").
                      addResourceLocations("classpath:/static/");
        }
    };
}

BUT WebMvcConfigurerAdapter is deprecated in Spring 5. How can I access the static resources now?

2条回答
叛逆
2楼-- · 2019-04-07 09:24

Just to add from the answer of @alfcope above:

The same objective can be achieved by directly extending WebMvcConfigurationSupport as suggested in the documentation

It seems like extending WebMvcConfigurationSupport serves the purpose of @EnableWebMvc and allows selectively override any desired default implementation and in this case addResourceHandlers. So the example code can be

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/resources/**")
                        .addResourceLocations("/public", "classpath:/static/")
                        .setCachePeriod(31556926);
        }

}
查看更多
祖国的老花朵
3楼-- · 2019-04-07 09:27

Spring 5 - Static Resources

From the documentation:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/resources/**")
                        .addResourceLocations("/public", "classpath:/static/")
                        .setCachePeriod(31556926);
        }

}
查看更多
登录 后发表回答