【发布时间】:2016-08-26 22:26:27
【问题描述】:
我正在尝试在抽象类中使用 Spring Cache,但它不起作用,因为据我所知,Spring 正在抽象类上搜索 CacheNames。我有一个使用服务层和 dao 层的 REST API。这个想法是为每个子类设置不同的缓存名称。
我的抽象服务类如下所示:
@Service
@Transactional
public abstract class AbstractService<E> {
...
@Cacheable
public List<E> findAll() {
return getDao().findAll();
}
}
抽象类的扩展如下所示:
@Service
@CacheConfig(cacheNames = "textdocuments")
public class TextdocumentsService extends AbstractService<Textdocuments> {
...
}
所以当我使用这段代码启动应用程序时,Spring 给了我以下异常:
Caused by: java.lang.IllegalStateException: No cache names could be detected on 'public java.util.List foo.bar.AbstractService.findAll()'. Make sure to set the value parameter on the annotation or declare a @CacheConfig at the class-level with the default cache name(s) to use.
at org.springframework.cache.annotation.SpringCacheAnnotationParser.validateCacheOperation(SpringCacheAnnotationParser.java:240) ~[spring-context-4.1.6.RELEASE.jar:?]
我认为这是因为 Spring 在抽象类上搜索 CacheName,尽管它是在子类上声明的。
尝试使用
@Service
@Transactional
@CacheConfig
public abstract class AbstractService<E> {
}
导致同样的异常;使用
@Service
@Transactional
@CacheConfig(cacheNames = "abstractservice")
public abstract class AbstractService<E> {
}
也不例外,但是 Spring Cache 为每个子类使用相同的缓存名称,并忽略子类上定义的缓存名称。有什么想法可以解决这个问题吗?
【问题讨论】:
-
您找到解决问题的方法了吗?
-
很遗憾没有。
-
那太糟糕了。我通过在所有子类中重复“findAll”方法快速解决了这个问题,使用可缓存注释并在每个子类中调用 super.findAll()。
-
恕我直言,这可能与 java 中的注释不继承这一事实有关。
标签: java spring spring-mvc inheritance caching