1. Overview
AspectJ is a powerful tool for handling cross-cutting concerns like logging, security, and transaction management in Java applications. A common use case is applying an aspect to all methods within a specific package. In this tutorial, we’ll learn to create a pointcut in AspectJ that matches all methods in a package, with step-by-step code examples.
To learn more about AspectJ, check out our comprehensive AspectJ tutorials.
2. Maven Dependencies
When running an AspectJ program, the classpath should contain the classes and aspects, along with the AspectJ runtime library aspectjrt:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.22.1</version>
</dependency>
In addition to the AspectJ runtime dependency, we’ll also need to include the aspectjweaver library to introduce advice to the Java class at load time:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.22.1</version>
</dependency>
3. What Is a Pointcut?
A pointcut in AspectJ is a core concept defining where an aspect should be applied in the code. Aspects manage cross-cutting concerns like logging, security, or transaction management. A pointcut specifies specific points, called join points, in the program’s execution where the aspect’s advice (or action) should run. These join points can be identified using different expressions, including method signatures, class names, or specific packages.
3.1. Key Concepts Related to Pointcuts
A join point is a specific moment in program execution where an aspect can be applied. This includes method calls, executions, object instantiations, and field accesses. Advice is the action an aspect takes at a join point. It can occur before (@Before), after (@After), or around (@Around) the joining point. A pointcut expression is a declaration that defines which join points should be matched. This expression follows a specific syntax that enables it to target method executions, field accesses, and more.
3.2. Pointcut Syntax
A pointcut expression usually has two key components: the type of join point and the signature pattern. The type of join point defines the event, including a method call, method execution, or constructor execution. The signature pattern identifies specific methods or fields using class, package, parameters, or return type criteria.
4. Pointcut Expression
To create a pointcut that matches all methods in a specific package, we can use the following expression:
execution(* com.baeldung.aspectj..*(..))
Here’s a breakdown of this expression:
- execution: The pointcut designator, specifies that we’re targeting method execution.
- *: A wildcard indicating any return type.
- com.baeldung.aspectj..*: Matches any class within the com.baeldung.aspectj package and any sub-packages.
- (..): Matches any method parameters.
4.1. Logging Aspect for All Methods in a Package
Let’s create an example aspect that logs the execution of all methods within a package named com.baeldung.aspectj:
@Before("execution(* com.baeldung.aspectj..*(..))")
public void pointcutInsideAspectjPackage(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getSimpleName();
System.out.println(
"Executing method inside aspectj package: " + className + "." + methodName
);
}
The pointcut expression in @Before targets all methods within the com.baeldung.aspectj package and its sub-packages.
Let’s create UserService in the service package:
@Service
public class UserService {
public void createUser(String name, int age) {
System.out.println("Request to create user: " + name + " | age: " + age);
}
public void deleteUser(String name) {
System.out.println("Request to delete user: " + name);
}
}
When the UserService methods run, the aspect pointcutInsideAspectjPackage() will log both methods. Now, let’s test our code:
@Test
void testUserService() {
userService.createUser("create new user john", 21);
userService.deleteUser("john");
}
The aspect pointcutInsideAspectjPackage() should be invoked right before the createdUser() and deleteUser() in the UserService class are executed:
Executing method inside aspectj package: UserService.createUser
Request to create user: create new user john | age: 21
Executing method inside aspectj package: UserService.deleteUser
Request to delete user: john
Next, let’s create another class named UserRepository in a different package called the repository package:
@Repository
public class UserRepository {
public void createUser(String name, int age) {
System.out.println("User: " + name + ", age:" + age + " is created.");
}
public void deleteUser(String name) {
System.out.println("User: " + name + " is deleted.");
}
}
When methods in the UserRepository class are executed, the aspect pointcutInsideAspectjPackage() will log both methods. Now, let’s test our code:
@Test
void testUserRepository() {
userRepository.createUser("john", 21);
userRepository.deleteUser("john");
}
The aspect pointcutInsideAspectjPackage() should be invoked right before the createdUser() and deleteUser() methods in the UserService class are executed:
Executing method inside aspectj package: UserRepository.createUser
User: john, age:21 is created
Executing method inside aspectj package: UserRepository.deleteUser
User: john is deleted.
4.2. Logging Aspect for All Methods in a Sub-Package
Let’s create an example aspect that logs the execution of all methods within a package named com.baeldung.aspectj.service:
@Before("execution(* com.baeldung.aspectj.service..*(..))")
public void pointcutInsideServicePackage(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getSimpleName();
System.out.println(
"Executing method inside service package: " + className + "." + methodName
);
}
The pointcut expression inside the @Before annotation (execution(* com.baeldung.aspectj.service..*(..))) matches all methods within the com.baeldung.aspectj.service package.
Next, let’s create another class named MessageService in the service package to provide additional test cases:
@Service
public class MessageService {
public void sendMessage(String message) {
System.out.println("sending message: " + message);
}
public void receiveMessage(String message) {
System.out.println("receiving message: " + message);
}
}
When any method of MessageService is executed, the aspect pointcutInsideServicePackage() will log both methods. Now, let’s test our code*:*
@Test
void testMessageService() {
messageService.sendMessage("send message from user john");
messageService.receiveMessage("receive message from user john");
}
The aspect pointcutInsideAspectjPackage() previously and pointcutInsideServicePackage() should be invoked right before the method sendMessage() and receiveMessage() in the MessageService class are called:
Executing method inside aspectj package: MessageService.sendMessage
Executing method inside service package: MessageService.sendMessage
sending message: send message from user john
Executing method inside aspectj package: MessageService.receiveMessage
Executing method inside service package: MessageService.receiveMessage
receiving message: receive message from user john
4.3. Logging Aspect by Excluding a Specific Package
Let’s create an example aspect that will exclude the execution of a specific package named com.baeldung.aspectj.service:
@Before("execution(* com.baeldung.aspectj..*(..)) && !execution(* com.baeldung.aspectj.repository..*(..))")
public void pointcutWithoutSubPackageRepository(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getSimpleName();
System.out.println(
"Executing method without sub-package repository: " + className + "." + methodName
);
}
The pointcut expression inside the @Before annotation (execution(* com.baeldung.aspectj..*(..)) && !execution(* com.baeldung.aspectj.repository..*(..))) matches all methods within the com.baeldung.aspectj package and its sub-packages and excluding the sub-package repository.
Now, let’s re-run our previous unit test. The aspect named pointcutWithoutSubPackageRepository() should be invoked right before all methods in the aspectj package while excluding the repository sub-package in this case:
Executing method inside aspectj package: UserService.createUser
Executing method inside service package: UserService.createUser
Executing method without sub-package repository: UserService.createUser
Request to create user: create new user john | age: 21
Executing method inside aspectj package: UserService.deleteUser
Executing method inside service package: UserService.deleteUser
Executing method without sub-package repository: UserService.deleteUser
Request to delete user: john
Executing method inside aspectj package: UserRepository.createUser
User: john, age:21 is created.
Executing method inside aspectj package: UserRepository.deleteUser
User: john is deleted.
Executing method inside aspectj package: MessageService.sendMessage
Executing method inside service package: MessageService.sendMessage
Executing method without sub-package repository: MessageService.sendMessage
sending message: send message from user john
Executing method inside aspectj package: MessageService.receiveMessage
Executing method inside service package: MessageService.receiveMessage
Executing method without sub-package repository: MessageService.receiveMessage
receiving message: receive message from user john
5. Conclusion
In this tutorial, we learned that a pointcut in AspectJ is a powerful tool for specifying exactly where aspect advice should be applied (such as to methods, classes, or fields).
Creating a pointcut to target all methods within the main package or a specific package is straightforward with AspectJ. We can also exclude certain packages if needed.
This approach is useful for applying the same logic such as logging or security checks across multiple classes and methods without duplicating code. By defining a pointcut for the desired package, we can keep your code clean and easy to maintain.
The code examples are available over on GitHub.