简体   繁体   中英

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?

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

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