【问题标题】:Writing a custom Spring @Cacheable annotation编写自定义 Spring @Cacheable 注解
【发布时间】:2013-11-25 18:54:19
【问题描述】:

我目前正在编写一个自定义 @Cacheable 注释,除了 Spring 的 @Cacheable 提供的那些之外,它还将采用额外的元数据属性。但是,Spring 需要知道如何解析这个新注解。我的理解是我需要扩展和覆盖 AnnotationCacheOperationSourcedetermineCacheOperations() 以便可以使用适当的解析新注释CacheableOperation 类从它初始化。这是正确的方法吗?

问候,

史蒂夫

【问题讨论】:

  • @Steve,你的问题解决了吗,如果可以,请分享一下。我也被这个问题阻止了。感谢您对此的帮助

标签: java spring caching


【解决方案1】:

视情况而定。

根据AnnotationCacheOperationSource javadoc

这个类读取Spring的Cacheable、CachePut和CacheEvict 注释并将相应的缓存操作定义暴露给 Spring 的缓存基础设施。这个类也可以作为基类 用于自定义 CacheOperationSource。

因此,如果您要求是/否的答案,是否可以扩展该类以获得 CacheOperationSource 的扩展行为,答案是肯定的。

但是,defineCacheOperations() 方法的作用是它使用了所有可用的 CacheAnnotationParsers。唯一默认的 CacheAnnotationParser 是 SpringCacheAnnotationParser。如果您有自定义的,只需让另一个类为您的注释实现 CacheAnnotationParser 。然后 Spring 应该会自动使用它。你可以看看 SpringCacheAnnotationParser source code 看看他们是怎么做的。


编辑:好的,我错了,这会自动发生。我的下一个建议是

  • 实现接口 CacheAnnotationParser,就像你显然已经做过的那样
  • 扩展 AnnotationCacheOperationSource 以便您将自己的 CacheAnnotationParser 除了 Spring 之一放在内部解析器集合中
  • 定义您的自定义 AnnotationCacheOperationSource 以使用与 Spring 相同的 id,因此它将覆盖 Spring 内部。如果 id 匹配,它应该干净地覆盖 Spring 一。这将是这样的:

    <bean id="annotationCacheOperationSource" class="com.company.YourCustomAnnotationCacheOperationSource" />

【讨论】:

  • 非常感谢 Eis 的回复。我已经考虑将 SpringCacheAnnotationParser 的 parseCacheableAnnotation() 方法复制到新的扩展 AnnotationCacheOperationSource 中,但是通过将其抽象为单独的 CacheAnnotationParser,您的方法更加清晰和正确。我不需要向 Spring 注册新的 CacheAnnotationParser 以使其被识别吗?我该怎么做?
  • @Steve Spring 通常的工作方式是您只需实现所需的接口,然后在 Spring 上下文中将实现它的类连接为 bean。然后根据界面自动正确使用。我认为这也适用于这种情况。
  • 我无法识别新的 CacheAnnotationParser。我在我的配置中使用缓存:注释驱动,并且在初始化期间,AnnotationDrivenCacheBeanDefinitionParser 创建了一个使用单个 SpringCacheAnnotationParser 的 AnnotationCacheOperationSource。我认为的一个解决方案是在我的配置中定义一个 AnnotationCacheOperationSource、CacheInterceptor 和 BeanFactoryCacheOperationSourceAdvisor(一个 cacheAdvisor)来初始化新的 pasrer。但是我们现在创建了 2 个 AnnotationCacheOperationSource bean;一个来自 Spring,一个来自我的应用程序。任何帮助表示赞赏。
  • @Steve 您使用的是哪个春季版本,顺便说一句?
  • @Steve 现在用另一个建议更新了我的答案
猜你喜欢
  • 1970-01-01
  • 2021-08-22
  • 2021-08-06
  • 2012-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
  • 2013-02-24
相关资源
最近更新 更多