Search code examples
springaopspring-aop

How to match two patterns in one pointcut expression


I want to define my pointcut to match two kinds of methods:

  1. all methods from class org.mypackage.Foo with names starting with "update"
  2. all methods from the same class with names starting with "delete"

I tried the following:

@Before("execution (* org.mypackage.Foo.update*(..) ) && execution(* org.mypackage.Foo.delete*(..) )")
public void verify()
{
  //verify if user has permission to modify...
}

It doesn't work. When I call either a Foo.update*() method or a Foo.delete*() method, verify() is not invoked.

How should I change it?


Solution

  • There are 2 option to match patterns in pointcut expression. The pointcut expression may be either a simple reference to a named pointcut, or a pointcut expression declared in place.

    1. By creating individual method for respective point cut. And using that method name as reference in @Before advice.
        @Pointcut("execution(* org.mypackage.Foo.update*(..))")
        private void fooUpdate() {}
        
        @Pointcut("execution(* org.mypackage.Foo.delete*(..))")
        private void fooDelete() {}
        
        @Before("fooUpdate() || fooDelete()")
        public void verify() {
          // verify if user has permission to modify...
        }
    
    1. Directly declaring pointcut expression in place.
        @Before("execution(* org.mypackage.Foo.update*(..)) || execution(* org.mypackage.Foo.delete*(..))")
        public void verify() {
          // verify if user has permission to modify...
        }