@Cacheablespring
@Cacheable 的做用 主要針對方法配置,可以根據方法的請求參數對其結果進行緩存數據庫
@Cacheable 做用和配置方法緩存
參數 | 解釋 | example |
---|---|---|
value | 緩存的名稱,在 spring 配置文件中定義,必須指定至少一個 | 例如: @Cacheable(value=」mycache」) @Cacheable(value={」cache1」,」cache2」} |
key | 緩存的 key,能夠爲空,若是指定要按照 SpEL 表達式編寫,若是不指定,則缺省按照方法的全部參數進行組合 | @Cacheable(value=」testcache」,key=」#userName」) |
condition | 緩存的條件,能夠爲空,使用 SpEL 編寫,返回 true 或者 false,只有爲 true 才進行緩存 | @Cacheable(value=」testcache」,condition=」#userName.length()>2」) |
實例spa
@Cacheable(value=「accountCache」),這個註釋的意思是,當調用這個方法的時候,會從一個名叫 accountCache 的緩存中查詢,若是沒有,則執行實際的方法(即查詢數據庫),並將執行的結果存入緩存中,不然返回緩存中的對象。這裏的緩存中的 key 就是參數 userName,value 就是 Account 對象。「accountCache」緩存是在 spring*.xml 中定義的名稱。code
@Cacheable(value="accountCache")// 使用了一個緩存名叫 accountCache public Account getAccountByName(String userName) { // 方法內部實現不考慮緩存邏輯,直接實現業務 System.out.println("real query account."+userName); return getFromDB(userName); }