```java
@Service
public class MyService {
@Autowired
private CacheManager cacheManager;
@Cacheable("myCache") // 指定快取名稱
public String getCachedData(String key) {
// 此方法的結果將被緩存
return expensiveDatabaseOperation(key);
}
@CachePut("myCache") // 更新緩存
public String updateCachedData(String key, String newValue) {
updateDatabase(key, newValue);
return newValue;
}
@CacheEvict("myCache") // 清除快取
public void clearCachedData(String key) {
deleteFromDatabase(key);
}
public void clearCacheItem(String key) {
// 根據條件調用快取清除操作
if (someCondition) {
cacheManager.getCache("myCache").evict(key);
}
}
public void clearCacheItem() {
cacheManager.getCache("myCache").clear();
}
}
```