Could some one provide a good snippet to construct and inject Google guava's CacheBuilder
into a dependent bean via Spring
xml?
To generalize, I need some examples in Spring
that illustrates construction of objects using builder pattern.
Guava default comes with spring boot server , if you need a specific version you have to override the default with specific version.
Guava Caches store values in RAM.
Guava cache stores key and object like ConcurrentHashMap. Guava cache is thread safe. The feature provided by Guava cache is basically same as ConcurrentHashMap but Guava cache is more preferable than ConcurrentHashMap in terms of cache optimization.
With the addition of CacheBuilderSpec in the next Guava release (release 12), you'll be able to create a CacheBuilder
bean in xml, using the CacheBuilder.from(String spec) static factory method.
It would look like this:
<bean id="legendaryCacheBuilder"
class="com.google.common.cache.CacheBuilder"
factory-method="from">
<constructor-arg value="maximumSize=42, expireAfterAccess=10m, expireAfterWrite=1h" />
</bean>
You could even externalize the configuration string into a .properties file, using Spring's PropertyPlaceholderConfigurer
.
Until then, you should use Sean Patrick Floyd's solution (which also has the advantage of being type-safe).
While it's possible to call arbitrary methods in Spring XML using the factory-method
attribute, you'll find that it's close to impossible for Builder-Pattern style chained calls.
Instead, use a FactoryBean
or Java-based container configuration for such complex scenarios. XML will not get you that far, I'm afraid.
Also wanted to add that you can use the Cache Spec directly in the Cache Manager if you're not interested in different Cache Builders for different Caches.
You're not required to specify each cache by name when initializing the Cache Manager, each new request for a Cache will build one based on the provided CacheBuilder, or in this case with the provided Cache Spec (which results in a corresponding CacheBuilder).
You're Spring XML ends up being extremely elegant:
<bean id="cacheManager" class="org.springframework.cache.guava.GuavaCacheManager">
<property name="cacheSpecification" value="maximumSize=300000,expireAfterWrite=10h" />
</bean>
Also note: don't forget to tell spring you are using caching by including something like this in your application config xml:
<cache:annotation-driven/>
Which you'll need to of course define:
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/cache classpath:org/springframework/cache/config/spring-cache-4.2.xsd"
If you're not doing something simple like this and you do want to have multiple CacheBuilders for different use cases then you will probably want to create your own Factory Class and Method.
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