
Spring Cache 中动态 Key 的处理方法
在使用 Spring Cache 的 @Cacheable 注解时,常常需要根据动态参数生成缓存 Key。直接使用动态参数会导致 "attribute value must be constant" 错误,因为 @Cacheable 的 key 属性值必须是常量表达式。本文介绍两种解决方法:
方法一:利用 Spring Bean 获取动态值
<code class="java">@Service
public class CurrentUserService {
private static final ThreadLocal<String> userIdThreadLocal = new ThreadLocal<>();
public void setUserId(String userId) {
userIdThreadLocal.set(userId);
}
public String getUserId() {
return userIdThreadLocal.get();
}
}</code>@Cacheable 注解中使用 SpEL 表达式引用 Bean 方法:<code class="java">@Cacheable(value = "shoppingCar", key = "#currentUserService.getUserId() + '_car'")
public Object getShoppingCarData() {
// ... your logic ...
}</code>方法二:使用 SpEL 表达式直接处理方法参数
<code class="java">@Cacheable(value = "mainFieldInfo", key = "{#currentId, '_car'}")
public Object getMainFieldInfo(String currentId) {
// ... your logic ...
}</code>@Cacheable 注解的 key 属性中,使用 SpEL 表达式 {#currentId, '_car'} 直接拼接 Key。#currentId 代表方法参数 currentId 的值。这两种方法都能有效解决 @Cacheable 注解 key 值必须为常量的限制,允许根据动态参数生成不同的缓存 Key,从而实现更灵活的缓存策略。 选择哪种方法取决于具体场景和代码结构,方法二更简洁直接,但方法一在某些复杂场景下可能更易于管理。
以上就是SpringCache中如何解决@Cacheable注解Key值必须为常量的限制?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号