How to Increase Embedded Tomcat Cache in Spring

If you see warnings like this when you fire-up your Spring Boot Web App using Embedded Tomcat than you probably need to increase Tomcat Cache.

The exact warning message is:

Unable to add the resource at [/WEB-INF/lib/blah-blah.jar] to the cache because there was insufficient free space available after evicting expired cache entries – consider increasing the maximum size of the cache.

This is pretty straightforward if our app was served up by Tomcat as a conventional WAR file. We’d simply increase our cache in the Tomcat /conf/context.xml file. Something like

<Resources cachingAllowed=”true” cacheMaxSize=”100000″ />

But our Tomcat is Embedded. Our solution is to create an instance of Spring Boot’s TomcatEmbeddedServletContainerFactory and customize the Tomcat Container Context before it used with the Tomcat Server. Notice we’re doing this in a @Configuration WebConfig class which extends WebMvcConfigurerAdapter.

Thanks to Alexander Hofmann who provided the above source on StackOverflow. You’ll also find the above in the NixMash Spring Source but copying and pasting from Alexander’s answer will be quicker. This Spring Guide on Embedded Servlet Containers is another excellent resource on customizing Embedded Tomcat.

So let’s fire-up our Spring Boot web app again with the additional cache.

Nice!

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.