gpt4 book ai didi

Spring AOP 不适用于 Feign Client

转载 作者:行者123 更新时间:2023-12-01 14:37:44 25 4
gpt4 key购买 nike

我有一个 aop 设置

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

如果我在服务层添加这个注释( @IgnoreHttpClientErrorExceptions ),
@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);
}
}

我的 AOP 被调用。

但是当我在我的 feign 层中添加这个注释( @IgnoreHttpClientErrorExceptions )时。
@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。

当我在 feign-layer 中添加注释时,知道为什么不调用 aop 吗?

依赖添加:
 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

最佳答案

方法上的注释不应该被继承。

因此,spring AOP 无法拦截您的方法。

事件 @Inherited仅支持从 superclass to subclasses. 继承

因此,在这种情况下,您应该尝试另一个切入点,具体取决于您的需要:

// 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 *+).*(..))")

关于Spring AOP 不适用于 Feign Client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51914315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com