有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

共 (1) 个答案

  1. # 1 楼答案

    Your question is a bit unclear. Am I guessing right that you have multiple @Around advice methods with identical method bodies and you want to factor out those method bodies into a helper method in order to avoid code duplication within your aspect(s)?

    是的,你是对的@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,只需向其添加另一个参数并相应地调用它