@Cacheble annotation on no parameter method

五迷三道 提交于 2019-12-03 01:59:43

It seems that Spring doesn't allow you to provide a static text for the cache key in the SPEL, and it doesn't include as default the name of the method on the key, so, you could be in a situation when two methods using the same cacheName and without a key would potentially cache different results with the same key.

The easiest workaround is to provide the name of the method as the key:

@Cacheable(value="usercache", key = "#root.methodName")
public string sayHello(){
return "test"
}

This would set sayHello as the key.

If you really need a static key, you should define a static variable in the class, and use #root.target:

public static final String MY_KEY = "mykey";

@Cacheable(value="usercache", key = "#root.target.MY_KEY")
public string sayHello(){
return "test"
}

You can find here the list of SPEL expressions that you can use in your key.

Cliff

Try adding single quotes around mykey. It's a SPEL expression, and the singles quotes make it a String again.

@Cacheable(value="usercache", key = "'mykey'")
Giggs

Add # in the key

@Cacheable(value="usercache", key = "#mykey")
public string sayHello(){
    return "test"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!