Close

Spring Boot - Setting Cache Period for Static Resources

[Last Updated: Dec 19, 2017]

In Spring Boot, we can set spring.resources.cache-period property to specify the cache period for the static resources in seconds. By default this value is zero. The value set to this property (say n) will cause the response header of Cache-Control:max-age=n to be sent to the browser.

Example

In this example, we are going to create a static page under default '/static' folder (see last tutorial for default locations).

src\main\resources\static\my-page.html

<!DOCTYPE html>
<html>
<body>
<h2>My Static page 9</h2>
</body>
</html>

src/main/resources/application.properties

spring.main.banner-mode=off 
spring.main.logStartupInfo=false
spring.resources.cache-period=10

Main Class

@SpringBootApplication
public class ExampleMain {
  public static void main(String[] args) throws InterruptedException {
      SpringApplication.run(ExampleMain.class, args);
  }
}

Output

In chrome's developer tools:

Refresh again:

See also 'Last-Modified', 'If-Modified-Since' and 'Cache-Control' headers info here and Spring MVC support for Cache-Control here.

Example Project

Dependencies and Technologies Used:

  • Spring Boot 1.5.9.RELEASE
    Corresponding Spring Version 4.3.13.RELEASE
  • spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • JDK 1.8
  • Maven 3.3.9

Boot Static Resource Cache Period Select All Download
  • static-resource-cache-period-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • static
          • application.properties

    See Also