title: Using EhCache in Spring 4 without XML
body: <p>Is there a way to initialize EhCache without xml in either Spring 4 or with Spring Boot?</p>
  
  <p>I noticed Spring Boot 1.0.0.RC3 doesn't have any ehcache dependencies but the <a href="https://spring.io/blog/2013/12/12/announcing-spring-framework-4-0-ga-release" rel="noreferrer">Spring 4.0GA release post</a> mentioned it has improved support for EhCache. Also, Spring 3 had the class <code>org.springframework.cache.ehcache.EhCacheCacheManager</code> but that's no longer part of the dependencies.</p>
  
  <p><strong>Edit:</strong>
  Spring 4 does have EhCache support. You must add the dependency:</p>
  
  <pre><code>&lt;groupId&gt;org.springframework&lt;/groupId&gt;
  &lt;artifactId&gt;spring-context-support&lt;/artifactId&gt;
  </code></pre>
  
  <p><strong>Edit2:</strong>
  I've tried the following and I think I'm close but I'm getting an error:</p>
  
  <pre><code>@Bean
  @Override
  public CacheManager cacheManager() {
      CacheConfiguration cacheConfiguration = new CacheConfiguration();
      cacheConfiguration.setName("primary");
      cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");
      cacheConfiguration.setMaxEntriesLocalHeap(0);
  
      net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
      config.addCache(cacheConfiguration);
  
      net.sf.ehcache.CacheManager cacheManager = new net.sf.ehcache.CacheManager(config);
      cacheManager.setName("EhCache");
  
      return new EhCacheCacheManager(cacheManager);
  }
  
  @Bean
  public EhCacheManagerFactoryBean factoryBean() {
      return new EhCacheManagerFactoryBean();
  }
  </code></pre>
  
  <p><em>Error</em></p>
  
  <pre><code>Caused by: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
  1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
  2. Shutdown the earlier cacheManager before creating new one with same name.
  The source of the existing CacheManager is: [Programmatically configured]
      at net.sf.ehcache.CacheManager.assertNoCacheManagerExistsWithSameName(CacheManager.java:590)
      at net.sf.ehcache.CacheManager.init(CacheManager.java:384)
      at net.sf.ehcache.CacheManager.&lt;init&gt;(CacheManager.java:263)
      at org.springframework.cache.ehcache.EhCacheManagerFactoryBean.afterPropertiesSet(EhCacheManagerFactoryBean.java:166)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
      ... 15 more
  </code></pre>