簡體   English   中英

如何在方法聲明中使用@around spring aop annotation?

[英]How can I use @around spring aop annotation on method declaration?

如何在方法聲明中使用@around spring AOP注釋? 實際上java類中有很多重復的代碼,所以我想優化它。只有@around執行值每次都會改變,3-4方法的方法定義相同。你能建議我能做什么這種情況下的代碼優化?在給定的例子中你可以看到nicdStatus和nicdPortStatus只是被改變了,所有的方法定義都是相同的。 請提供代碼優化的一些建議,因為我的java類中有重復的代碼。

@Around("execution(* dcp.casa.services.nicd.NicdController.**nicdStatus**(..)) && args(*, relationId,..)")
Object handleRunTest(final ProceedingJoinPoint joinPoint, final String relationId) {
    log.info("xyz");
    callAbc();
    return joinPoint.proceed();
}

@Around("execution(* dcp.casa.services.nicd.NicdController.nicdPortStatus(..)) && args(*, relationId,..)")
Object handleRunTest(final ProceedingJoinPoint joinPoint, final String relationId) {
    log.info("xyz");
    callAbc();
    return joinPoint.proceed();
}

AOP意味着你想攔截一​​些邏輯。 使用@around時,您已准備好在某些方法之前和之后放置一些邏輯。 這是刪除重復代碼的好方法。

你需要做什么:

1)找到具有重復代碼的所有方法。

2)將這些重復代碼抽象為一些方法。

3)使用正確的切入點配置。

這里有更多的例子。 希望可以幫助。

你的問題有點不清楚。 我是否正確地猜測你有多個具有相同方法體的@Around建議方法,並且你想將這些方法體分解為一個輔助方法,以避免你方面的代碼重復?

是的,你是對的@kriegaex。 你了解我的問題。

嗯,那么答案很簡單:重構就像重構任何其他Java類一樣:

package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
public class LoggingAspect {
  private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);

  private void callAbc() {}

  @Around("execution(* dcp.casa.services.nicd.NicdController.**nicdStatus**(..)) && args(*, relationId, ..)")
  public Object handleRunTestA(ProceedingJoinPoint joinPoint, String relationId) throws Throwable {
    return handleRunHelper(joinPoint);
  }

  @Around("execution(* dcp.casa.services.nicd.NicdController.nicdPortStatus(..)) && args(*, relationId, ..)")
  public Object handleRunTestB(ProceedingJoinPoint joinPoint, String relationId) throws Throwable {
    return handleRunHelper(joinPoint);
  }

  private Object handleRunHelper(ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("xyz");
    callAbc();
    return joinPoint.proceed();
  }
}

如果helper方法也需要訪問String relationId ,只需添加另一個參數並相應地調用它。

暫無
暫無

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

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