@Cacheable(value="users", key="#id")
key屬性是用來指定Spring緩存方法的返回結果時對應的key的。該屬性支持SpringEL表達式。當咱們沒有指定該屬性時,Spring將使用默認策略生成key。咱們這裏先來看看自定義策略,至於默認策略會在後文單獨介紹。
1. 自定義策略是指咱們能夠經過Spring的EL表達式來指定咱們的key。這裏的EL表達式能夠使用方法參數及它們對應的屬性。使用方法參數時咱們能夠直接使用「#參數名」或者「#p參數index」。下面是幾個使用參數做爲key的示例。緩存
@Cacheable(value="users", key="#id") public User find(Integer id) { return null; } @Cacheable(value="users", key="#p0") public User find(Integer id) { return null; } @Cacheable(value="users", key="#user.id") public User find(User user) { return null; } @Cacheable(value="users", key="#p0.id") public User find(User user) { return null; }
2.除了上述使用方法參數做爲key以外,Spring還爲咱們提供了一個root對象能夠用來生成key。經過該root對象咱們能夠獲取到如下信息。app
當咱們要使用root對象的屬性做爲key時咱們也能夠將「#root」省略,由於Spring默認使用的就是root對象的屬性:less
@Cacheable(value={"users", "xxx"}, key="caches[1].name") public User find(User user) { return null; }
若是要調用當前類裏面的方法:code
@RequestMapping(value = "/dept/data") @ResponseBody @Cacheable(value = "echartDeptDataCache", key = "#root.target.getFormatKey()", unless = "#result == null") public Map<String, Object> deptChartData() { return null; }
/** * 生成key - echartDeptDataCache * * @param * @return */ public String getFormatKey() { return ShiroUtils.getLoginName() + "echartDeptDataCache"; }
劃重點:要調用的方法要是public的。orm