使用@CachePut注解时如何获取方法返回值的ID作为缓存key
解决方案
Spring Cache 内置了 SpEL 表达式变量 #result,可直接指向当前注解修饰方法的返回值,你只需要修改 @CachePut 的 key 属性值为 #result.你的ID字段名 即可。
示例修改后的代码
@CachePut(value = "dishDTOs", key = "#result.id") @CacheEvict(cacheNames = "dishDTOList", allEntries = true) public DishResponseDTO createDish(DishCreationDTO dishCreationDTO) { int restaurantId = dishCreationDTO.getRestaurantId(); var restaurant = restaurantRepository.getById(restaurantId); var dish = DishMapper.toDish(dishCreationDTO, restaurant); return toDishResponseDTO(dishRepository.save(dish)); }
注意事项
- 上述代码默认你的
DishResponseDTO类中ID对应的字段名为id,如果实际字段名是dishId等其他命名,将key属性里的id替换为实际字段名即可 - 该方式仅在方法有非空返回值时生效,你的业务逻辑里方法固定返回保存后的DTO,不存在空指针风险
内容的提问来源于stack exchange,提问作者user16722881
相关产品推荐
相关产品推荐

