2

Is it possible to write AOP for Spring RestTemplate class using spring AOP or Aspectj. EX:

@Around("execution(* org.springframework.web.client.RestTemplate.getFor*(..))")  

Thanks

kriegaex
  • 63,017
  • 15
  • 111
  • 202
thangavel vel
  • 21
  • 1
  • 2
  • With AspectJ it's definitely possible. – Nándor Előd Fekete Nov 04 '16 at 17:04
  • Please, can you given any link s to refer... – thangavel vel Nov 04 '16 at 17:06
  • 2
    [The AspectJ Development Environment Guide](http://www.eclipse.org/aspectj/doc/released/devguide/). You'll need to decide if you want to go with compile-time weaving vs load-time weaving. If you can, go with compile-time weaving. For compile-time weaving, refer to http://www.mojohaus.org/aspectj-maven-plugin/. For load-time weaving, refer to http://www.eclipse.org/aspectj/doc/released/devguide/ltw-configuration.html – Nándor Előd Fekete Nov 04 '16 at 17:11
  • I have tried load-time weaving. Still I couldn't write AOP for "org.springframework.web.client.RestTemplate." class. Reference [link](http://www.codesenior.com/en/tutorial/AspectJ-Load-Time-Weaving-in-Spring). – thangavel vel Nov 12 '16 at 15:44

1 Answers1

2

I had the same issue and couldn't make it work with AOP.

However, in this case, there is a workaround. Since RestTemplate extends InterceptingHttpAccessor, you can intercept all requests coming through theRestTemplate object.

Sample configuration that logs all HTTP requests :

@Bean
public RestTemplate restTemplate() {

    RestTemplate restTemplate = new RestTemplate();

    // (...)
    // setup code for the RestTemplate object

    restTemplate.getInterceptors().add((request, body, execution) -> {
        logger.info("HTTP {} request to {}", request.getMethod(), request.getURI());
        return execution.execute(request, body);
    });

    return restTemplate;
}

While this is not equivalent to using an aspect, you can get similar functionality with interceptors and pretty minimal configuration.

christopheml
  • 2,444
  • 17
  • 25