java Spring 5 - 如何提供静态资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46567681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:16:41  来源:igfitidea点击:

Spring 5 - How to provide static resources

javaspringspring-mvcresourcesspring-webflux

提问by John Mendes

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?

但是 WebMvcConfigurerAdapter 在 Spring 5 中已被弃用。我现在如何访问静态资源?

回答by alfcope

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

}

回答by Masud

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. So the example code can be

似乎扩展 WebMvcConfigurationSupport 服务于 @EnableWebMvc 的目的,并允许有选择地覆盖任何所需的默认实现,在这种情况下是 addResourceHandlers。所以示例代码可以是

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

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

}