我有以下程序。周围的方法被调用,但为什么不是主要方法?据我所知,方法是在方法执行之前或之后执行的。围绕方法被调用,但是为什么它不打印主要方法,即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
答案 0 :(得分:1)
周围建议:围绕连接点的建议,例如方法 调用。这是最有力的建议。围绕建议 可以在方法调用之前和之后执行自定义行为。它 还负责选择是否继续进行连接点 或通过返回自己建议的方法来捷径建议的方法执行 返回值或引发异常。
我们需要在@Around咨询中使用ProceedingJoinPoint
org.aspectj.lang.ProceedingJoinPoint
使用@Around批注来声明周围建议。首先 建议方法的参数必须为ProceedingJoinPoint类型。 在建议的正文中,在 ProceedingJoinPoint使基础方法执行。的 前进方法也可以传入Object []。数组中的值 用作方法执行时的参数。
代码应为
@Around("execution(* com.inno.aop.EmployManager.*(..))")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Around method getting called");
joinPoint.proceed();
}
答案 1 :(得分:0)
Around方面会拦截呼叫,您可以决定是否继续进行真实的课堂。在这段代码片段中,您仅调用System.out.println
而不运行真实类的方法...
您应该致电:
@Around(...)
public void logAround(JoinPoint joinPoint) {
jointPoint.proceed(); // + handle exceptions if required
}
答案 2 :(得分:0)
在用@Around注释的方法中,需要调用joinPoint.proceed()
,然后才调用被拦截的方法。另外,
joinPoint.proceed(Object[] args)
。 @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();
}
}