方法 getById
位于名为 AbstractCachedResult
的抽象类中。
public abstract class AbstractCachedResult<T extends BaseResource> {
@Cacheable(value = "dynamicName")
public T getById(String id){
//program logic
}
}
许多其他服务类将从该类继承。例如:
public class UserService extends AbstractCachedResult<User> {
//program logic
}
由于我在抽象类中设置 @Cacheable(value = "dynamicName")
,因此我无法知道该方法返回的类的类型。我需要能够动态获取类的名称,以便对于来自其继承类的每个方法调用都使用正确的缓存。
我遇到了另一篇帖子。在这里,他们将实体类名称作为参数传递,但我无法这样做。我需要动态获取返回数据的类型,以便我可以使用 @Caching 注释,这是#2 解决方案。有办法做到这一点吗?
The method getById
is located in an Abstract class named AbstractCachedResult
.
public abstract class AbstractCachedResult<T extends BaseResource> {
@Cacheable(value = "dynamicName")
public T getById(String id){
//program logic
}
}
Many other service classes will be inheriting from this class. For ex :
public class UserService extends AbstractCachedResult<User> {
//program logic
}
Since I am setting the @Cacheable(value = "dynamicName")
in the abstract class I wouldn't be able to know the type of the class that was returned by the method. I need to be able to get the name of the class dynamically so that for each method invocation from its inherited class the correct cache is used.
I have came across another post. Here they are passing the entity class name as a parameter which I cannot do. I need to get the type of the returned data dynamically so that I could us the @Caching annotation which is the #2 soluton. Is there a way to do this?
发布评论
评论(1)
可以说,最简单、最明显的解决方案,特别是对于维护人员来说,是重写子类中的 getById(:String) 方法,如下所示:
或者,您可以实现“自定义”
CacheResolver
(请参阅doc 和 Javadoc) 能够检查(目标)子类的类通用签名。最后,在底层,Spring 的缓存抽象是使用 Spring AOP 实现的。对于真正的低级控制,应该可以编写自定义 AOP 拦截器,这与 Spring 的默认 CacheInterceptor 不同(Javadoc)。如果需要,您自己的 AOP 建议甚至可以相对于可缓存建议进行排序。
老实说,我认为我上面提出的第一个选项是最好的方法。并非每个服务类都需要缓存
getById(:String)
操作的结果。缓存实际上取决于数据的事务性质以及数据更改的频率。运用你最好的判断力。
Arguably, the simplest and most obvious solution, especially for maintainers, would be to override the
getById(:String)
method in the subclass, like so:Alternatively, you might be able to implement a "custom"
CacheResolver
(see doc and Javadoc) that is able to inspect the class generic signature of the (target) subclass.Finally, under-the-hood, Spring's Cache Abstraction is implemented with Spring AOP. For real, low-level control, it should be possible to write custom AOP Interceptor not unlike Spring's default
CacheInterceptor
(Javadoc). Your own AOP Advice could even be ordered relative to the Cacheable Advice, if needed.Honestly, I think the first option I presented above is the best approach. Not every service class may need to cache the result of the
getById(:String)
operation. Caching really depends on the transactional nature of the data and how frequently the data changes.Use your best judgement.