Java 是否将实例字段作为缓存键?
我正在使用Java 是否将实例字段作为缓存键?,java,spring,spring-cache,Java,Spring,Spring Cache,我正在使用org.springframework.cache.annotation.Cacheable进行方法级缓存 public class Customer { private Long id; @Cacheable("customer",key="this.id") public CustomerAddress findCustomerAddress() {...} } 我想缓存密钥为id的customer对象。但我没有id作为方法参数。我将其作为实例字段?您不可能轻松做到这一点,
org.springframework.cache.annotation.Cacheable
进行方法级缓存
public class Customer {
private Long id;
@Cacheable("customer",key="this.id")
public CustomerAddress findCustomerAddress() {...}
}
我想缓存密钥为id的customer对象。但我没有id作为方法参数。我将其作为实例字段?您不可能轻松做到这一点,上面的代码有两种味道:
- 您正试图将
缓存在地址
缓存中客户
- 您试图缓存的对象似乎没有自己的标识。然后,您更希望缓存
(它有一个)而不是子组件客户
@Cacheable(cacheNames = "customer", keyGenerator="customerKeyGenerator")
public CustomerAddress findCustomerAddress() {...}
}
然后在一些@配置
类中
@Bean
public KeyGenerator customerKeyGenerator() {
}
的API非常简单。例如,您可以检查目标实例是否是
客户
,然后检索id值。每个客户
都是由Spring管理的吗?一种更常见的方法是在服务/DAO层中使用@Cacheable
,而不是直接在域对象上使用(通常Spring根本不会管理域对象)。换句话说,您可以通过将findCustomerAddress
移动到服务层并发送用户ID作为其输入参数来解决这个问题。此代码仅在服务层中。我刚才给出了我想要实现的示例。ES CustomerAddress.id是您想要用作缓存密钥的属性吗?