我正在尝试@Cacheable从同一个类中调用一个方法:
@Cacheable(value = "defaultCache", key = "#id")
public Person findPerson(int id) {
return getSession().getPerson(id);
}
public List<Person> findPersons(int[] ids) {
List<Person> list = new ArrayList<Person>();
for (int id : ids) {
list.add(findPerson(id));
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
并希望结果findPersons也被缓存,但@Cacheable注释被忽略,并且findPerson每次都执行方法.
我在这里做错了什么,或者这是有意的吗?
与spring框架中的提交有关https://github.com/spring-projects/spring-framework/commit/5aefcc802ef05abc51bbfbeb4a78b3032ff9eee3
初始化设置为从afterPropertiesSet()到afterSingletonsInstantiated()的后续阶段
简而言之:这可以防止在@PostConstruct用例中使用缓存时缓存工作.
更长的版本:这可以防止您使用的用例
在methodB上使用@Cacheable创建serviceB
使用@PostConstruct调用serviceB.methodB创建serviceA
@Component
public class ServiceA{
@Autowired
private ServiceB serviceB;
@PostConstruct
public void init() {
List<String> list = serviceB.loadSomething();
}
Run Code Online (Sandbox Code Playgroud)这导致org.springframework.cache.interceptor.CacheAspectSupport现在不进行初始化,因此不会缓存结果.
protected Object execute(CacheOperationInvoker invoker, Object target, Method method, Object[] args) {
// check whether aspect is enabled
// to cope with cases where the AJ is pulled in automatically
if (this.initialized) {
//>>>>>>>>>>>> NOT Being called
Class<?> targetClass = getTargetClass(target);
Collection<CacheOperation> operations = getCacheOperationSource().getCacheOperations(method, targetClass);
if (!CollectionUtils.isEmpty(operations)) { …Run Code Online (Sandbox Code Playgroud)