问题描述:

I have successfully use AOP with Spring applications, but surprisingly I stuck on a simple java project. now I'm trying to implement very simple AOP java application, but it doesn't work. Here are basic classes:

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 {

}

As you can see it is very simple app with 4 classes. IntelliJ detects AOP advise properly, but it is ignored when I running the app. I'm sure there is a samll mistake which I just can't detect.

Please help!

网友答案:

The code is okay, for me the console log looks like this:

myTrace:before call 
myTrace:before call 
inside Service
myTrace:after call 
myTrace:after call 
Hello World

Probably you are used from Spring AOP to get only one interception for the pointcut @annotation(TimeableMetric), but in opposite to Spring AOP only knowing execution() pointcuts, AspectJ also supports call() pointcuts. So if you change your pointcut to @annotation(TimeableMetric) && execution(* *(..)), the log becomes:

myTrace:before call 
inside Service
myTrace:after call 
Hello World

As for the question how to get the aspects applied, you need to

  • compile the application with the AspectJ compiler ajc and then
  • run it with the AspectJ runtime aspectjrt.jar on the classpath.
相关阅读:
Top