Skip to main content
 首页 » 编程设计

spring-mvc中排除特定文件(静态资源)被缓存 | Spring 启动网络

2025年12月25日49langtianya

我有一个 Spring Boot 应用程序,下面是注​​册资源处理程序的代码:

@Configuration     
public class MyAppConfig extends WebMvcConfigurerAdapter { 
       ... 
        @Override 
        public void addResourceHandlers(ResourceHandlerRegistry registry) { 
            registry.addResourceHandler("/resources/js/**")          
            .addResourceLocations("/resources/js/").setCachePeriod(31536000); 
          //in same directory where all the js files placed, 
          //I want to cache all the files in that directory 
          //except for one file i.e. prop.js 
          /*registry.addResourceHandler("/resources/js/prop.js") 
           .addResourceLocations("/resources/js/").setCachePeriod(0);*/ 
       } 
       ... 
    } 

有些事情我需要理解,即。
1、addResourceHandler的参数是什么意思?
2. addResourceLocations 参数是什么意思?
3. 有没有办法显式阻止 prop.js 被缓存?

可能有与 prop.js 处于同一级别的文件,我希望缓存所有其他文件。

请您参考如下方法:

  1. addResourceHandler 方法中,您可以指定 URL 或 URL 模式。
  2. addResourceLocations 中,您指定一个实际包含静态资源的有效目录(或者可能是多个用逗号分隔的目录)。

最后,您在 Web 服务器上的 URL 和目录之间进行了简单的映射。

  • 如果您只想禁用文件 prop.js 的缓存,请尝试以下操作:

    registry 
        .addResourceHandler("/resources/js/**/prop.js") 
        .addResourceLocations("/resources/js/") 
        .setCachePeriod(0); 
    registry 
        .addResourceHandler("/resources/js/**") 
        .addResourceLocations("/resources/js/") 
        .setCachePeriod(31536000);