我們知道緩存方法的調用是通過spring aop切入的調用的。在一個類調用另一個類中的方法可以直接的簡單調用,但是如果在同一個類中調用自己已經通過spring托管的類中的方法該如何實現呢?
先來段代碼:
public
List<Long> getSkuIdsBySpuId(
long
spuId) {
ItemComposite itemComposite =
this
.getItemComposite(spuId);
///能走下面的緩存嗎?
if
(itemComposite!=
null
) {
if
( CollectionUtils.isNotEmpty(itemComposite.getItemSkus())) {
return
itemComposite.getItemSkus().stream().map(itemSku -> itemSku.getId()).collect(Collectors.toList());
}
}
return
Collections.emptyList();
}
@Cacheable
(value =
"getItemComposite"
, key =
"#spuId"
)
public
ItemComposite getItemComposite(
long
spuId) {
//select from db...
}
public
List<Long> getSkuIdsBySpuId(
long
spuId) {
ItemCacheManager itemCacheManager = (ItemCacheManager)AopContext.currentProxy();
if
(itemComposite!=
null
) {
if
( CollectionUtils.isNotEmpty(itemComposite.getItemSkus())) {
return
itemComposite.getItemSkus().stream().map(itemSku -> itemSku.getId()).collect(Collectors.toList());
}
}
return
Collections.emptyList();
}
@Cacheable
(value =
"getItemComposite"
, key =
"#spuId"
)
public
ItemComposite getItemComposite(
long
spuId) {
//select from db...
}
可以看到修改的地方是通過調用AopContext.currentProxy的方式去拿到代理類來調用getItemComposite方法。這樣就結束了?不是,通過調試發現會拋出異常:java.lang.IllegalStateException: Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.
繼續查找資料,csdn上一篇文章正好有篇文章http://blog.csdn.net/z69183787/article/details/45622821是講述這個問題的,他給的解決方法是在applicationContext.xml中添加一段<aop:aspectj-autoproxy proxy-target-class="true"expose-proxy="true"/>
。但是與我們的系統不同的是,我們系統是通過spring-boot來啟動的,目前都是通過annotation來代替配置文件的,所以我們必須找到一個annotation來代替這段配置,發現在ApplicationMain中加入@EnableAspectJAutoProxy(proxyTargetClass=true)然后添加maven依賴
<
dependency
>
<
groupId
>org.springframework.boot</
groupId
>
<
artifactId
>spring-boot-starter-aop</
artifactId
>
</
dependency
>
可以解決我們的問題,這時候你一定認為事情可以大功告成了,但是真正的坑來了:我們的spring-boot版本是1.3.5,版本過低,這種注解必須是高版本才能支持,有種想死的感覺。。。。怎么辦?
還是想想csdn上的那篇文章,通過配置文件是可以解決的,那么我們就在spring boot中導入配置文件應該就沒問題了啊。
於是我們可以配置一個aop.xml文件,文件內容如下:
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
xsi:schemaLocation="http://www.springframework.org/schema/beans
<
aop:aspectj-autoproxy
proxy-target-class
=
"true"
expose-proxy
=
"true"
/>
</
beans
>
@ImportResource
(locations =
"aop.xml"
)