Synesso
Synesso

Reputation: 38978

Can I annotate a method as cacheable in Spring?

I would like to use an annotation that marked the result of a method call as cacheable. When provided it would use a caching provider to cache the output for the given input. For example:

@Cacheable
public Bar doExpensiveCalculation(Foo foo) {
    Bar bar = jiggeryPokeryWith(foo);
    return bar;
}

...

Foo foo1 = new Foo(...);
Foo foo2 = new Foo(...);

Bar bar1 = doExpensiveCalculation(foo1);
Bar bar2 = doExpensiveCalculation(foo2);
Bar bar3 = doExpensiveCalculation(foo1);
// no calculation done on previous line, cached result == bar1

At the end of this example the cache would contain

{doExpensiveCalculation(foo1) -> bar1, 
 doExpensiveCalculation(foo2) -> bar2}

I am sure this is possible using AOP. As Spring does both AOP and caching, it seems it would be a natural fit for this use case.

Does such a feature exist?

Upvotes: 0

Views: 817

Answers (2)

checklist
checklist

Reputation: 12930

the google code is not required anymore as spring has it out of the box: http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html#cache-store-configuration-ehcache

Upvotes: 1

Bozho
Bozho

Reputation: 597106

This module has what you want. (But it is actually pretty straightforward to implement)

Upvotes: 1

Related Questions