简体   繁体   English

Spring 5 - 如何提供静态资源

[英]Spring 5 - How to provide static resources

I am trying provide static resources in my web application and I tried: 我正在尝试在我的Web应用程序中提供静态资源,我试过:

@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? 但是在Spring 5中不推荐使用WebMvcConfigurerAdapter。如何立即访问静态资源?

Spring 5 - Static Resources Spring 5 - 静态资源

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);
        }

}

Just to add from the answer of @alfcope above: 只是从上面的@alfcope的答案添加:

The same objective can be achieved by directly extending WebMvcConfigurationSupport as suggested in the documentation 通过直接扩展WebMvcConfigurationSupport可以实现相同的目标,如文档中所建议的那样

It seems like extending WebMvcConfigurationSupport serves the purpose of @EnableWebMvc and allows selectively override any desired default implementation and in this case addResourceHandlers. 似乎扩展WebMvcConfigurationSupport服务于@EnableWebMvc的目的,并允许有选择地覆盖任何所需的默认实现,在这种情况下是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);
        }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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