22

I am trying to define a pointcut, that would catch every method that is annotated with (i.e.) @CatchThis. This is my own annotation.

Moreover, I'd like to have access to the first argument of the method, which will be of Long type. There may be other arguments too, but I don't care about them.


EDIT

This is what I have right now. What I don't know is how to pass the first parameter of the method annotated with @CatchThis.

@Aspect 
public class MyAspect {
    @Pointcut(value = "execution(public * *(..))")
    public void anyPublicMethod() {
    }

    @Around("anyPublicMethod() && @annotation(catchThis)")
    public Object logAction(ProceedingJoinPoint pjp, CatchThis catchThis) throws Throwable {
        return pjp.proceed();
    }
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
emesx
  • 12,555
  • 10
  • 58
  • 91

1 Answers1

26

Something like this should do:

@Aspect
public class MyAspect{

    @Pointcut(value="execution(public * *(..))")
    public void anyPublicMethod() {
    }

    @Around("anyPublicMethod() && @annotation(catchThis) && args(.., Long ,..)")
    public Object logAction(
        ProceedingJoinPoint pjp, CatchThis catchThis, Long long)
        throws Throwable {

        return pjp.proceed();
    }
}
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • I've updated my post. Could you do the same with your snippet? I'd be very grateful. – emesx Oct 19 '11 at 07:32
  • Thanks. is it possible, to catch methods which have ONE Long argument that is not necessarily the first argument - it can be first, second.. or last? – emesx Oct 19 '11 at 07:46
  • `Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'piano' defined in class path resource [beans.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut` This is what I get trying to use your aspect.. I am lost. + I removed the first .., from the args(..) - the error was different then. – emesx Oct 19 '11 at 09:34
  • I tried the answer, which I was looking for the whole afternoon, and it worked, in a very simple way. I was surprised how strong the aspecj and spring could be, as well as my Intellij IDEA knew the pointcut was valid by static code analysis. Unfortunately, I could find the answer for this specific question on spring official doc. – Chen Yi Jan 19 '15 at 09:52
  • Will this pointcut expression also cover object which are not spring managed? Meaning if I use @CatchThis annotation on a simple POJO, will the pointcut expression evaluate it? – Himalay Majumdar Apr 29 '16 at 19:02