1

I've declared two aspects as foo & bar over a function runFunc and I want to capture time taken to run the function runcFunc & Bar in Foo, but it is capturing the time only for runFunc. Bar is running independently.

I want that If I put two annotation over a function, the 1st annotation should wrap the 2nd annotation and the 2nd one should wrap the function runfunc. How can I achieve that?

Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86
  • Hi Pankaj. You asked me to answer this, but I have to make an assumption that the reason you want to do this is to find performance problems in non-trivial code. If that's not your objective, I'm not much help. If that is your objective, I think a far more effective method is not measuring (like this code) but [*stackshots*](https://stackoverflow.com/a/378024/23771). – Mike Dunlavey May 22 '17 at 20:08

1 Answers1

0

It turns out aspect can wrap other aspects just as easily as they can wrap a function.

Following code works.

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Foo {}


@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Bar {}


@Aspect
@Component
public class A {

    @Around("@annotation( foo )")
    public void func1(final ProceedingJoinPoint pjp, Foo foo) throws Throwable {
        System.out.println("foo start");
        pjp.proceed();
        System.out.println("foo end");
    }
}


@Aspect
@Component
public class B {

    @Around("@annotation( bar )")
    public void func2(final ProceedingJoinPoint pjp, Bar bar) throws Throwable {
        System.out.println("bar start");
        pjp.proceed();
        System.out.println("bar end");
    }
}

The below code:

@Foo
@Bar
public void runFunc(){
    System.out.println("Inside Run.runFunc");
}

outputs the following:

foo start
bar start
Inside Run.runFunc
bar end
foo end
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86