Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 是否将实例字段作为缓存键?_Java_Spring_Spring Cache - Fatal编程技术网

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是您想要用作缓存密钥的属性吗?