I use Ehcache 2 + spring boot
. Here is my config:
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
}
ehcache.xml - in resources.
Now I want to use Ehcache 3 + spring boot
and Java config instead xml but I haven't found any example for this. My questions:
1) Why almost all examples are based on xml? How can this be better than java config?
2) How can I configure Ehcache 3 using java config in spring boot without using xml?
Here is an equivalent java configuration for creating the Ehcache manager bean.
ApplicationConfig.java
@Configuration
@EnableCaching
public class ApplicationConfig {
@Bean
public CacheManager ehCacheManager() {
CachingProvider provider = Caching.getCachingProvider();
CacheManager cacheManager = provider.getCacheManager();
CacheConfigurationBuilder<String, String> configuration =
CacheConfigurationBuilder.newCacheConfigurationBuilder(
String.class,
String.class,
ResourcePoolsBuilder
.newResourcePoolsBuilder().offheap(1, MemoryUnit.MB))
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(20)));
javax.cache.configuration.Configuration<String, String> stringDoubleConfiguration =
Eh107Configuration.fromEhcacheCacheConfiguration(configuration);
cacheManager.createCache("users", stringDoubleConfiguration);
return cacheManager;
}
}
ServiceImpl.java
@Service
public class ServiceImpl {
@Cacheable(cacheNames = {"users"})
public String getThis(String id) {
System.out.println("Method called............");
return "Value "+ id;
}
}
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
There are a lot of examples. I personally am a fan of the Java configuration.
Here are the main official examples:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With