In Spring AOP, the execution
pointcut expression is one of the most commonly used pointcut designators. It is used to specify join points based on method execution within the application. The execution
pointcut expression has the following syntax:
execution(modifiers-pattern? return-type-pattern declaring-type-pattern? method-name-pattern(param-pattern) throws-pattern?)
Here's an explanation of each component of the execution
pointcut expression:
- modifiers-pattern (optional):
- Specifies the modifiers of the method (e.g.,
public
,private
,protected
,static
, etc.). - If omitted, it matches methods with any modifier.
- Specifies the modifiers of the method (e.g.,
- return-type-pattern:
- Specifies the return type of the method (e.g.,
void
,java.lang.String
,*
, etc.). - Use
*
to match any return type.
- Specifies the return type of the method (e.g.,
- declaring-type-pattern (optional):
- Specifies the declaring type or class where the method is defined.
- If omitted, it matches methods in any class.
- method-name-pattern:
- Specifies the name of the method (e.g.,
doSomething
,*
, etc.). - Use
*
to match any method name.
- Specifies the name of the method (e.g.,
- param-pattern:
- Specifies the parameter types of the method.
- The parameter pattern is specified within parentheses
()
. - Use fully qualified class names to match specific parameter types.
- Use
*
to match any parameter type. - Use
..
to match any number of parameters of any type.
- throws-pattern (optional):
- Specifies the exception types thrown by the method.
- Use fully qualified exception class names to match specific exception types.
- If omitted, it matches methods that do not throw any exceptions.
Example execution
pointcut expressions:
execution(* com.example.service.*.*(..))
: Matches any method execution within thecom.example.service
package.execution(public * com.example.service.UserService.*(..))
: Matches any public method execution in theUserService
class within thecom.example.service
package.execution(* com.example.service.UserService.find*(String))
: Matches any method execution in theUserService
class within thecom.example.service
package that starts withfind
and accepts a singleString
parameter.execution(* com.example.service.*.*(..) throws java.lang.Exception)
: Matches any method execution within thecom.example.service
package that throwsjava.lang.Exception
.
These execution
pointcut expressions provide a flexible and powerful way to select method execution join points within Spring applications for applying advice. They allow developers to precisely target specific methods based on various criteria such as method signatures, modifiers, return types, parameter types, and exception types.