2017-10-04 197 views
0

我想在我的web應用程序提供靜態資源,我想:春天5 - 如何提供靜態資源

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

但WebMvcConfigurerAdapter在彈簧5不贊成我現在如何才能訪問靜態資源?

回答

3

Spring 5 - Static Resources

從文檔:

@Configuration 
@EnableWebMvc 
public class WebConfig implements WebMvcConfigurer { 

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

} 
0

只是爲了從@alfcope以上的答案添加:

相同的目的可以通過直接延伸WebMvcConfigurationSupport如documentation建議來實現

好像是擴展WebMvcConfigurationSupport服務的目的@ EnableWebMvc,並允許有選擇地覆蓋任何需要的默認實現,在這種情況下addResourceHandlers。所以示例代碼可以是

@Configuration 
public class WebConfig extends WebMvcConfigurationSupport { 

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

}