如何在方法声明中使用@around spring aop注释?

时间:2019-05-28 20:36:30

标签: java spring-boot methods spring-aop spring-annotations

如何在方法声明中使用@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();
}

2 个答案:

答案 0 :(得分:0)

AOP表示您想拦截一些逻辑。使用@around时,您准备将一些逻辑放在方法的前后。这是删除重复代码的好方法。

您需要做什么:

1)查找所有重复代码的方法。

2)将那些重复的代码抽象为某些方法。

3)使用正确的切入点进行配置。

here有更多示例。希望能有所帮助。

答案 1 :(得分:0)

  
    

您的问题有点不清楚。我猜对了吗,您有多个具有相同方法主体的@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();
  }
}

如果辅助方法也需要访问String relationId,只需向其添加另一个参数并相应地调用它即可。

相关问题