【发布时间】:2021-09-03 07:04:39
【问题描述】:
我正在尝试做一个简单的缓存任务。我有一个Holiday 对象,它有两个字段:referenceDate 和isHoliday。然后,我有一个方法可以向 rest api 发出 HTTP 请求,以检查日期是否为假期。我想要实现的是:如果当前缓存的Holiday 对象与作为参数传递的对象具有相同的referenceDate,则返回缓存的值。我有一个特定的类来执行该检查。代码如下:
假期班
@AllArgsConstructor
@Getter
public class Holiday {
public LocalDate referenceDate;
public boolean isHoliday;
}
CacheService 类
@DomainService
public class CacheService {
@Autowired
private CacheManager cacheManager;
public boolean isReferenceDateCached(final LocalDate referenceDate){
final Holiday holiday = (Holiday) cacheManager.getCache("holiday").get("holidaycheck");
return(holiday.getReferenceDate().equals(referenceDate));
}
}
HolidatInfraService 类
@AllArgsConstructor
@Service
@Slf4j
public class HolidayInfraService {
@Autowired
private final CacheService cacheService;
@Cacheable(value = "holiday", key = "holidaycheck", condition = "#cacheService.isReferenceDateCached(#holidayDateToCheck)")
public Holiday isHoliday(final LocalDate holidayDateToCheck) {
//some code to call a rest api
}
}
这是我在尝试holidayInfraService.isHoliday(someDate) 时从单元测试中得到的错误:
org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method isReferenceDateCached(java.time.LocalDate) on null context object
从这个异常消息看来,cacheService 是空的。但是,当我调试代码并进入isHoliday 时,cacheService 不为空。也许注释运行时它还没有自动装配?这也是我第一次与 SPEL 合作,所以也许那里也有一些东西。如果事实上cacheService 还没有自动连接,是否有解决方法?
【问题讨论】:
标签: spring spring-boot java-11 spring-el