在 Spring Boot 中使用 ECache 时是否应该指定键类型和值类型?

Should I specify key-type and value-type when using ECache in Spring Boot?

我看过很多文章,其中指定了这些参数,例如:

    <cache alias="dishDTOs" uses-template="default">
    <key-type>java.lang.Integer</key-type>
    <value-type>com.topjava.graduation.restaurant.dto.DishResponseDTO</value-type>
</cache>

但这有什么意义呢?即使没有它们,一切似乎也能正常工作,而且,如果我指定这些,我就会有这个例外

Invalid value type, expected : com.topjava.graduation.restaurant.dto.DishResponseDTO but was : java.util.ArrayList

正在测试的方法(只需将这 2 个一一调用即可):

        @Cacheable(value = "dishDTOs", key = "-2")
    public List<DishResponseDTO> getAll() {
    // code
}
    @Cacheable(value = "dishDTOs", key = "#dishId")
    public DishResponseDTO getOne(int dishId) {
    // code

}

您可能应该使用两个不同的缓存。在第一种情况下,您试图将列表(getAll 方法的return 类型)保存到为单个 DishResponseDTO 指定的缓存中。这就是你得到例外的原因。

如果您不指定类型,缓存将采用 Object,因此您将没有任何类型安全。例如,参见 Ehcache docs.