aspectj

@Before advice is not called


Java 8

package com.myproject.javatestmavenbom.module1.aop;

public class Main {
  public static void main(String[] args) {
    UserService userService = new UserService();
    userService.createUser("create new user john", 21);
    userService.deleteUser("john");
  }
}
package com.myproject.javatestmavenbom.module1.aop;

public class UserService {
  public void createUser(String name, int age) {
    System.out.println("UserService: Request to create user: " + name + " | age: " + age);
  }

  public void deleteUser(String name) {
    System.out.println("UserService: Request to delete user: " + name);
  }
}
package com.myproject.javatestmavenbom.module1.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class MyAspect {
  // Before calling any method in the com.myproject.javatestmavenbom.module1.aop.UserService
  @Before("call(* com.myproject.javatestmavenbom.module1.aop.*(..))")
  public void beforeUserServiceMethodCall(JoinPoint joinPoint) {
    System.out.println("MyAspect: Calling a UserService method: " + joinPoint.getSignature().toShortString());
  }
}

But when I start the app, I get the following result:

UserService: Request to create user: create new user john | age: 21
UserService: Request to delete user: john

So, why is method beforeUserServiceMethodCall doesn't call before createUser/deleteUser?

MyAspect: Calling a UserService method:

Solution

  • In your pointcut call(* com.myproject.javatestmavenbom.module1.aop.*(..)), the .* near the end can represent either a sub-package, class or method name. Assuming, it represents class UserService, then a subsequent .* for the method name is missing. Either of the following will work:

    If you are new to AspectJ, please also note that there are both call() and execution() pointcuts, which intercept different things. Most of the time, you want execution(), but there are many valid use cases for call(), too.

    MyAspect: Calling a UserService method: UserService.createUser(..)
    UserService: Request to create user: create new user john | age: 21
    MyAspect: Calling a UserService method: UserService.deleteUser(..)
    UserService: Request to delete user: john