Pointcut expressions help you pick specific places in your code to add extra behavior without changing the original code.
Pointcut expressions in Spring Boot
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? method-name-pattern(param-pattern) throws-pattern?)
The execution keyword is the most common way to write pointcut expressions.
Use * as a wildcard to match any part, like any method name or any return type.
com.example.service package.execution(* com.example.service.*.*(..))
execution(public * *(..))
find in UserRepository class.execution(* com.example.repository.UserRepository.find*(..))
delete that take a single Long parameter and return void in controller package.execution(void com.example.controller.*.delete*(Long))
This example shows a logging aspect that runs before any method in the com.example.service package. When createUser runs, the aspect prints a message first.
package com.example.aop; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore() { System.out.println("A method in service package is about to run."); } } // Sample service class package com.example.service; import org.springframework.stereotype.Service; @Service public class UserService { public void createUser() { System.out.println("User created."); } } // Main application to run package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import com.example.service.UserService; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(DemoApplication.class, args); UserService userService = context.getBean(UserService.class); userService.createUser(); } }
Pointcut expressions are very flexible and can match many method patterns.
Be careful with wildcards to avoid matching too many methods unintentionally.
Use Spring Boot DevTools or your IDE debugger to test if your pointcuts are working as expected.
Pointcut expressions select where extra code runs without changing original methods.
Use execution() with wildcards to match methods by name, package, or parameters.
They help add logging, security, or other features cleanly and easily.