亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使變量可用于連接點而不更改方法簽名并稍后使用它

使變量可用于連接點而不更改方法簽名并稍后使用它

繁星淼淼 2023-06-28 16:27:53
使用 @Around 方面和 Spring boot 時。在 joinPoint 執行之前創建變量、在 joinPoint 執行期間使其可用以收集其中的數據以及在 joinPoint 執行之后使用變量中收集的數據的最佳方法是什么?假設是多線程環境。@Aspect@EnableAspectJAutoProxypublic class SomeConfig {    @Around(value = "@annotation(path.to.my.annotation.here)", argNames = "specificArg")    public void doLogic(ProceedingJoinPoint joinPoint) throws Throwable {        //create local variable X for thread execution here        try{            joinPoint.proceed(); //or joinPoint.proceed(Object[]);        }        finally {        //use local variable X to do some logic        }    }}不想使用自定義注釋更改方法簽名。任何設計模式或實現示例都會有很大幫助。謝謝!
查看完整描述

1 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

您可以創建一個保險箱ThreadLocal并設置所需的變量,然后使用它。


public class VariableContext {


    private static ThreadLocal<String> currentVariable = new ThreadLocal<String>() {

        @Override

        protected String initialValue() {

            return "";

        }

    };


    public static void setCurrentVariable(String tenant) {

        currentVariable.set(tenant);

    }


    public static String getCurrentVariable() {

        return currentVariable.get();

    }


    public static void clear() {

        currentVariable.remove();

    }


}

您可以在這里或其他課程中使用它。


@Aspect

@EnableAspectJAutoProxy

public class SomeConfig {


    @Around(value = "@annotation(path.to.my.annotation.here)", argNames = "specificArg")

    public void doLogic(ProceedingJoinPoint joinPoint) throws Throwable {


        //create local variable X for thread execution here

        try{

            joinPoint.proceed(); //or joinPoint.proceed(Object[]);

        }

        finally {

        //use local variable X to do some logic

            VariableContext.setCurrentVariable("someValue");

            String result = VariableContext.getCurrentVariable();


        }

    }

}


查看完整回答
反對 回復 2023-06-28
  • 1 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號