Java Spring AOP:Making advice work for PostMappings that belong only to certain classes in a package

1.1k Views Asked by At

Hello i am trying to apply logging to my app by using aop.At this moment i can apply the advice on all the PostMapping methods from the application by using this pointcut.

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void postAction() {

    }

this is the advice

 @Before("postAction()")
    public void beforePost(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder
                .getRequestAttributes())).getRequest();
        String name = request.getParameter("firstName");
        logger.info(name);
    }

i don't want this.i want the advice to apply to only the PostMappings that handle User Objects and i guess this refers to the 3 controllers that handle the postmappings.In this case my package structure is this.

src>main>java>com>example>myApp>controller>(the 3 classes i want are here:EmployeeController,StudentController,UserController)

How do i make this pointcut

  @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")

apply only to the 3 classes above?

1

There are 1 best solutions below

6
On BEST ANSWER

What about combining several pointcus; adding those to your existing one:

@Pointcut("within(com.example.myApp.controller.EmployeeController)")
public void employeeAction() {

}

@Pointcut("within(com.example.myApp.controller.StudentController)")
public void studentAction() {

}

@Pointcut("within(com.example.myApp.controller.UserController)")
public void userAction() {

}

Then, in your advice, you could use:

@Before("postAction() && (employeeAction() || studentAction() || userAction())")