1

I want to use the @Cachable annotation on one of my methods, but I have the problem, that the result depends on an attribute of a spring bean that is not part of the method signature.

So I want something like this:

@Cachable(value="mycache", key="#id, #myspringbean.referenceId")
MyResult myMethod(int id);

I guess these are actually two problems: How to get use a composite key and how to use another spring bean in the expression.

The problem of how to use a composite key can probably be solved like in this SO question: @Cacheable key on multiple method arguments

However, I could not find anythig about how to reference to another spring bean in this expression. Is it possible and if yes, how?

Community
  • 1
  • 1
Tim
  • 2,051
  • 17
  • 36

2 Answers2

2

You can have a lot a details on SpEL in the Spring documentation (http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/expressions.html). As you can see, you can use bean references using the @myBean syntax. You have to include a bean resolver in your context to do that.

funkygono
  • 426
  • 3
  • 5
  • Ok, from what I see in the logs `@myBean` syntax seems to do what I want. But I do not know how to include a bean resolver in my context. Can you give an example or link for it? I googled for it but could not find anything that worked... – Tim Feb 04 '13 at 08:35
0

It's not possible to use the current Spring bean name. I think I would use the following pattern so that each bean object will have it's own "key-space" see also What can be the default key generator. As for the problem above one can use:

@Cachable(value="mycache", key = "{#id, #root.targetClass.getDeclaredField('attribute').get(#root.target)}")
MyResult myMethod(int id);

just make sure your attribute is public

Haim Sulam
  • 316
  • 1
  • 5