使用参数的Spring Cache Key

时间:2015-08-17 17:10:09

标签: spring

我有一个类,其中包含属性ID,名称和年龄。

我想使用id和name来缓存Person对象。

我的方法是
@Cacheable(value =“person”,key =“#p.id + p.name”)
getPerson(人物p)

问题是,我如何在getPerson()上使用缓存注释......就像这样。

1 个答案:

答案 0 :(得分:0)

使用注释可以连接值以创建密钥(我读过但未测试过调试符号可能会被删除,因此参数应该被引用为“p0”)。

@Cacheable(value="person", key="#p0.id.concat(‘:’).concat(#p0.name)")

否则,它将基于Person类equals()和hashCode()进行缓存,就像使用Person对象作为Map中的键一样。

所以,例如:

public class Person {
    String id;
    String name;
    Number age;

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Person))
            return false;
        Person other = (Person) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
}