簡體   English   中英

Spring AOP:在方法之間交換信息

[英]Spring AOP: exchanging information between methods

假設我有一個名為MyServlet的類,其目的是響應用戶請求:

@Component
public class MyServlet
{
    public void accept(String clientName, int clientID)
    {
        System.out.println("Processing client:" + clientName + " with ID: " + clientID);
    }
}

一般來說,在我們嘗試調試我們的應用程序之前,為用戶的請求提供服務可能是我們想要記錄的事情。 所以如果我能在調用accept()之前透明地發生這種行為,我真的很喜歡它。 對於這個人,一個Helper類可以提供一個日志功能,我們將用@Before裝飾@Before

@Aspect
@Component
@EnableAspectJAutoProxy
public class Helper
{
    @Before("execution(public void show())")
    public void log()
    {
        System.out.println("Logging data...");
    }
}

但是,能夠獲取提供給accept() (在本例中為Stringint )並將其傳遞給log()對我來說真的很有用,因為它可以讓我准確記錄用戶和他們的 ID 進入我使用的任何日志存儲。 我怎樣才能做到這一點?

您可以通過注入JoinPoint實例並在其上調用getArgs()方法來訪問代理方法的參數。 下面的示例片段。

@Before("execution(* com.sample.SomeClass.doSometning(..))")
public void doSomethingBefore(JoinPoint joinPoint) {
   Object[] args = joinPoint.getArgs();
   for (Object arg: args) {
       // do whatever you like with the arguments
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM