是否可以使用Spring AOP或Aspectj为Spring RestTemplate类和任何外部jar类编写AOP

时间:2016-11-04 17:03:53

标签: spring aspectj spring-aop aspectj-maven-plugin

是否可以使用spring AOP或Aspectj为Spring RestTemplate类编写AOP。 EX:

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

由于

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,无法使其与AOP一起使用。

但是,在这种情况下,有一种解决方法。自RestTemplate扩展InterceptingHttpAccessor以来,您可以拦截通过RestTemplate对象发出的所有请求。

记录所有HTTP请求的示例配置:

@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;
}

虽然这不等同于使用方面,但您可以使用拦截器和非常小的配置获得类似的功能。