Caching web content in Spring MVC Annotation Config

I support hosting static web resources (css/js/img/fonts/etc) outside of your web application, in a simple CDN (content distribution network) with a simple application server like nginx.

However, if your infrastructure does not exist, using these configs in your Spring MVC app would help greatly. This WebConfig class is the equivalent to web.xml.

public class WebConfig extends WebMvcConfigurerAdapter
    public void addResourceHandlers(ResourceHandlerRegistry registry)
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(2592000);  // 30 days for internal
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/").setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic());  // 1 year for external

WebJars is something we are trying out. It packages web resources into JARs and you can use them with maven / gradle as dependencies. I would still prefer CDN, but again, if you don’t have the infrastructure already setup, this seems like a good option.

tested with

Spring 4.2.5-RELEASE


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s