Search code examples
spring-dataspring-aopspring-data-rest

Spring AOP Pointcut for Spring Data Rest Controller (EndPoint)


I would like to do something on every api call to my spring boot app. I use Spring AOP to achieve this. Using:

@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() {
}

@Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
public void restController() {
}

@After("(controller() || restController())")
public void loggingAdvice(JoinPoint joinPoint) {
   // TODO: do something
}

Using that I can get all the event when API is being called. However, I am also using spring rest data for crud mechanism that automatically generate API end point, for example:

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
    User findByEmail(String email);
}

The question is, can I create a point cut for every API end point that is generated by spring rest data?


Solution

  • Following pointcut will target all the RESTful endpoint calls made at "/users"

    Considering the package of UserRepository is rg.so.example.datarest

    @Pointcut("execution(* rg.so.example.datarest.UserRepository.*(..))")
    public void dataRest() {
    }
    

    A more generic pointcut to target all the Repository implementations in a package rg.so.example.datarest would be

    @Pointcut("execution(* rg.so.example.datarest..*(..))")