Spring AOP not working for Feign Client

风流意气都作罢 提交于 2019-12-07 16:19:47

问题


I having an aop-setup

@Target({ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface IgnoreHttpClientErrorExceptions { }

@Aspect
@Component
public class IgnoreHttpWebExceptionsAspect {

@Around(value = "@annotation(annotation)", argNames = "joinPoint, annotation")
public Object ignoreHttpClientErrorExceptions(ProceedingJoinPoint joinPoint, IgnoreHttpClientErrorExceptions annotation)
  throws Throwable {
try {
  //do something
 } catch (HttpClientErrorException ex) {
  //do something
 }
}

If I add this annotation(@IgnoreHttpClientErrorExceptions) in service layer,

@Service
public class SentenceServiceImpl implements SentenceService {

 @Autowired
 VerbClient verbClient;

 @HystrixCommand(ignoreExceptions = {HttpClientErrorException.class})
 @IgnoreHttpClientErrorExceptions
 public ResponseEntity<String> patch(String accountId, String patch) {
    return verbClient.patchPreferences(accountId, patch);
 }
}

My AOP is invoked.

But when I add this annotation(@IgnoreHttpClientErrorExceptions) in my feign layer.

@FeignClient(value = "account")
@RequestMapping(value = "/url")
public interface VerbClient {

  @RequestMapping(value = "/{id}/preferences", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE)
  @IgnoreHttpClientErrorExceptions
  ResponseEntity<String> patchPreferences(@PathVariable("id") String accountId, String patchJson);
}

AOP is not invoked.

Any idea why aop is not get invoked, when I add the annotation in feign-layer?

Dependency added:

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-aop</artifactId>
 </dependency>

回答1:


Annotation on method is not supposed to inherited.

Hence spring AOP cannot intercept your methods.

Event @Inherited only support inheritance from superclass to subclasses.

So in this case, you should try another pointcut, depend on your need:

// Match all method in interface VerbClient and subclasses implementation
@Around(value = "execution(* com.xxx.VerbClient+.*(..))")

// Match all method in interface VerbClient and subclasses implementation
@Around(value = "execution(* com.xxx.VerbClient+.*(..))")

// Match all method `patchPreferences` in interface VerbClient and subclasses implementation
@Around(value = "execution(* com.xxx.VerbClient+.patchPreferences(..))")

// Or make IgnoreHttpClientErrorExceptions work for Type, 
// and match all method with in annotated interface and subclass implementation
// (@Inherited must be used)
// By this way, you can mark your VerbClient feign interface with this annotation
@Around(value = "execution(* (com.yyy.IgnoreHttpClientErrorExceptions *+).*(..))")


来源:https://stackoverflow.com/questions/51914315/spring-aop-not-working-for-feign-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!