4

I am trying to create a cache key with multiple parameter values.

@Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id")
private JSONObject getData(String name, String id) throws Exception {

From the above scenario, I name is a mandatory field while id is optional. I want to create key in such a way that,

  1. If name = "test" and id = null, cache key must be cache_name_test
  2. If name = "test" and id = "2", cache key must be cache_name_test_2

Currently, the key is forming something like "cache_name_test_null" if the id is not passed in the parameter value

Is it possible to create such key with @Cacheable annotation?

1 Answer 1

4

Solution

It's doable, but you need to wrap 2 @Cachable annotations in a @Caching annotation.

@Caching(
      cacheable = {
            @Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id", condition = "#id != null"),
            @Cacheable(cacheNames = "cache_name_", key = "#name", condition = "#id == null")
      }
    )
public JSONObject getData(String name, String id) throws Exception {

Note on private methods

You are using the @Caching annotation on a private method. This doesn't work. Those annotations only work on public methods being called from outside the class. See this Stack Overflow answer: https://stackoverflow.com/a/16899739/2082699

Sign up to request clarification or add additional context in comments.

3 Comments

This works with public methods, but the condition #id != null is not working
According to the official SPEL manual, this should work tho. Could you maybe add your current code? Maybe the problem is somewhere else?
I made a mistake by giving incorrect key name in the condition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.