我已经成功地将AOP与Spring应用程序一起使用,但令人惊讶的是我坚持使用一个简单的java项目。现在我试图实现非常简单的AOP java应用程序,但它不起作用。以下是基本课程:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class MySimpleLoggerAspect {
@Around("@annotation(TimeableMetric)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("myTrace:before call ");
Object retVal = null;
try {
retVal = joinPoint.proceed();
} finally {
System.out.println("myTrace:after call ");
}
return retVal;
}
}
public class SampleClass {
@TimeableMetric
public String doService(String in){
System.out.println("inside Service");
return in;
}
}
public class Tester {
public static void main(String[] args) {
System.out.println(new SampleClass().doService("Hello World"));
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface TimeableMetric {
}
正如您所看到的,它是一个非常简单的应用程序,有4个类。 IntelliJ正确检测AOP建议,但在运行应用程序时会被忽略。我确定有一个我无法察觉的小错误。 请帮忙!
答案 0 :(得分:1)
代码没问题,对我来说控制台日志如下所示:
myTrace:before call
myTrace:before call
inside Service
myTrace:after call
myTrace:after call
Hello World
可能你是从Spring AOP中使用了一个拦截器来获取切入点@annotation(TimeableMetric)
,但与Spring AOP相反只知道execution()
切入点,AspectJ也支持call()
切入点。因此,如果您将切入点更改为@annotation(TimeableMetric) && execution(* *(..))
,则日志将变为:
myTrace:before call
inside Service
myTrace:after call
Hello World
关于如何应用方面的问题,你需要