简体   繁体   中英

Injecting Google guava cache builder into bean via Spring

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM