如何让Spring @Cacheable在AspectJ方面工作?

编程入门 行业动态 更新时间:2024-10-14 14:22:51
本文介绍了如何让Spring @Cacheable在AspectJ方面工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了一个AspectJ方面,它在spring应用程序中运行良好。现在我想使用spring Cacheable注释添加缓存。

I created an AspectJ aspect which runs fine within a spring application. Now I want to add caching, using springs Cacheable annotation.

要检查@Cacheable是否被拾取,我使用的是不存在的缓存管理器的名称。常规运行时行为是抛出异常。但在这种情况下,没有抛出任何异常,这表明@Cacheable注释未应用于拦截对象。

To check that @Cacheable gets picked up, I'm using the name of a non-existing cache manager. The regular run-time behavior is that an exception is thrown. But in this case, no exception is being thrown, which suggests that the @Cacheable annotation isn't being applied to the intercepting object.

/* { package, some more imports... } */ import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.cache.annotation.Cacheable; @Aspect public class GetPropertyInterceptor { @Around( "call(* *.getProperty(..))" ) @Cacheable( cacheManager = "nonExistingCacheManager", value = "thisShouldBlowUp", key = "#nosuchkey" ) public Object intercepting( ProceedingJoinPoint pjp ) throws Throwable { Object o; /* { modify o } */ return o; } }

鉴于我的Aspect已经工作,我怎么能让@Cacheable在它上面工作?

Given that my Aspect is working already, how can I make @Cacheable work on top of it?

推荐答案

你可以通过使用Spring常规依赖注入机制并注入一个类似的结果 org.springframework.cache.CacheManager 进入您的方面:

You can achieve similar results, by using Spring regular dependency injection mechanism and inject a org.springframework.cache.CacheManager into your aspect:

@Autowired CacheManager cacheManager;

然后你可以在周围的建议中使用缓存管理器:

Then you can use the cache manager in the around advice:

@Around( "call(* *.getProperty(..))" ) public Object intercepting( ProceedingJoinPoint pjp ) throws Throwable { Cache cache = cacheManager.getCache("aopCache"); String key = "whatEverKeyYouGenerateFromPjp"; Cache.ValueWrapper valueWrapper = cache.get(key); if (valueWrapper == null) { Object o; /* { modify o } */ cache.put(key, o); return o; } else { return valueWrapper.get(); } }

更多推荐

如何让Spring @Cacheable在AspectJ方面工作?

本文发布于:2023-11-28 13:43:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642646.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:工作   Spring   Cacheable   AspectJ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!