Search code examples
javaspring-mvcspring-securityspring-data-restspring-security-oauth2

Custom Logic with Injected Values when using Spring Data Rest


I want to convert an existing web service to take advantage of spring-data-rest.

How can I implement custom logic with injected values (specifically an OAuth2 Principal) on top of spring data rest to keep existing functionality ?

For example, say I want to override the GET method for /person/1 to contact an auditing web service before it goes on to return the data of person 1.

Right now, before using spring-data-rest, I would have:

@RequestMapping(value = "/person/{id}", method = RequestMethod.GET)
public void getPerson(@RequestBody ...., Principal principal)
{
      /* Let Big Brother know that principal.getName() is doing this */
      return thePerson;
}

How would I do something like this with Spring Data Rest generated endpoints?


Solution

  • Thanks for the suggestions. I found out that what works best (for me) in this case is what Dave Syer suggested and to just go with AspectJ.

    In the end this will allow you to add custom logging logic, or anything else really, to the methods of a Spring Data JPA Repository:

    @Component
    @Aspect
    public class MyRepositoryAuditor {
    
        // pointcut on all methods with any arguments inside MyRepository
        @Pointcut("execution(public * example.jpa.repositories.MyRepository.*(..) )")
        public void publicRepositoryMethod() {
        }
    
        // if they return normally
        @AfterReturning("publicRepositoryMethod()")
        public void publicRepositoryMethod(JoinPoint jp) throws Throwable {
    
            String methodName = jp.getSignature().getName();
    
            .... perform logging ....
        }
    }