Spring 中的周围注释

Around Annotation in Spring

我有以下程序。正在调用 around 方法,但为什么不调用 main 方法?据我所知,周围的方法在方法执行之前或之后被执行。这里围绕方法被调用,但为什么它不打印主要方法,即 getEmploy();.

@Configuration
public class App extends Thread{

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.scan("com.inno.aop");
        context.refresh();
        EmployManager emp = (EmployManager) context.getBean("employManager");
        emp.getEmploy();
        context.close();
    }

}


@Service
public class EmployManager {

    public void getEmploy() {
        System.out.println("Here is your employ" );
    }
    public void getEmp() {
        System.out.println("Here is your emp" );
    }
}


@Aspect
@Component
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class EmployAspect {

     @Around("execution(* com.inno.aop.EmployManager.*(..))")
     public void logAround(JoinPoint joinPoint) {
         System.out.println("Around method getting called");
    }

}



Output:

Around method getting called

Around aspect拦截调用,你可以决定是否进行真正的class。在这段代码中,你只是调用 System.out.println 而不是 运行 真正的 class 方法...

您应该致电:

@Around(...)
public void logAround(JoinPoint joinPoint) {
   jointPoint.proceed();  // + handle exceptions if required
}

在@Around注解的方法中,需要调用joinPoint.proceed(),则只会调用被拦截的方法。另外,

  1. 确保提取方法参数并将其传递给 joinPoint.proceed(Object[] args)
  2. Return joinPoint.proceed 从您的 logAround() 方法返回的对象,以防被拦截的方法不是 void。
@Aspect
@Component
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class EmployAspect {

    @Around("execution(* com.inno.aop.EmployManager.*(..))")
    public void logAround(JoinPoint joinPoint) {
        System.out.println("Around method getting called");
        joinPoint.proceed();
    }
}

来自documentation

Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

我们需要使用 ProceedingJoinPoint@Around 建议

org.aspectj.lang.ProceedingJoinPoint

Around advice is declared by using the @Around annotation. The first parameter of the advice method must be of type ProceedingJoinPoint. Within the body of the advice, calling proceed() on the ProceedingJoinPoint causes the underlying method to execute. The proceed method can also pass in an Object[]. The values in the array are used as the arguments to the method execution when it proceeds.

代码应该是

 @Around("execution(* com.inno.aop.EmployManager.*(..))")
 public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
     System.out.println("Around method getting called");
     joinPoint.proceed();
 }