spring-boot

Prevent caching index.html file using spring-boot


I am using spring-boot and want to prevent caching of index.html but cache all other resources, I have put the resource files on my classpath and prevented caching using the following.

Currently I am doing the following which is caching all files.

@Configuration
public class StaticResourceConfig extends WebMvcConfigurerAdapter {

    private static final int SEVEN_DAYS_IN_SECONDS = 604800;

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:frontend/dist/")
                .setCachePeriod(SEVEN_DAYS_IN_SECONDS);
        super.addResourceHandlers(registry);
    }

}

The index.html file is located at frontend/dist/index.html


Solution

  • I managed to do it this way:

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    
       registry.addResourceHandler("/index.html")
                .addResourceLocations("classpath:frontend/dist/index.html")
                .setCachePeriod(0);
    
       registry.addResourceHandler("/assets/**")
                .addResourceLocations("classpath:frontend/dist/assets")
                .setCachePeriod(SEVEN_DAYS_IN_SECONDS);
    
        super.addResourceHandlers(registry);
    }