自定義註解 Redis失效原因分析

2021-08-21 09:36:50 字數 1603 閱讀 3793

概述在使用自定義註解形式的@redis做快取時,@redis失效,分析原因。

例項應用商店中根據imeisncode來查詢安裝列表

源**

@service("installedrecordservice")

public class installedrecordserviceimpl implements installedrecordservice

}

但是發現快取不成功。

原因aop的原理圖如下:

也就是說我們首先呼叫的是aop**物件而不是目標物件。但是我們使用this.getinstalledapk(imeisncodes.get(i))時,this表示的是當前的物件,而不是**物件,因此註解失效。

解決方法

解決方法1將getinstalledapks()方法放在另外的乙個類中進行呼叫,就不會出現這種問題了。**省略。

解決方法2暴露aop**物件:

仍然在同乙個類中呼叫**,但是改為如下的形式:

@service("installedrecordservice")

public class installedrecordserviceimpl implements installedrecordservice

return proxy;

} static object setcurrentproxy(object proxy)

else

return old;

}}

(1)在進入**物件之後通過aopcontext.sercurrentproxy(proxy)暴露當前**物件到threadlocal,並儲存上次threadlocal繫結的**物件為oldproxy

(2)接下來我們可以通過 aopcontext.currentproxy() 獲取當前**物件;

(3)在退出**物件之前要重新將threadlocal繫結的**物件設定為上一次的**物件,即aopcontext.sercurrentproxy(oldproxy)。

解決方法3往實現類中注入自身。

仍然在同乙個類中呼叫**,但是改為如下的形式:

@service("installedrecordservice")

public class installedrecordserviceimpl implements installedrecordservice{

//注入自身

@resource

private installedrecordservice installedrecordservice;

@resource

@override

public void getinstalledapks() {

if (imeisncodes != null && imeisncodes.size()> 0) {

for(int i=0;i綜述在乙個類內部呼叫時,被呼叫方法的aop宣告將不起作用。

自定義註解

target elementtype.field retention retentionpolicy.runtime public inte ce setvalue以上就是乙個自定義的註解,下面來進行說明。target elementtype.field 表示支援該註解的程式元素,field就是屬性...

自定義註解

三個重要元註解 target 即註解的作用域,用於說明註解的使用範圍 即註解可以用在什麼地方,比如類的註解,方法註解,成員變數註解等等 elemenettype.constructor 構造器宣告 elemenettype.field 域宣告 包括 enum 例項 elemenettype.loca...

自定義註解

三個重要元註解 target 即註解的作用域,用於說明註解的使用範圍 即註解可以用在什麼地方,比如類的註解,方法註解,成員變數註解等等 elemenettype.constructor 構造器宣告 elemenettype.field 域宣告 包括 enum 例項 elemenettype.loca...