【问题标题】:Spring AOP not working for Feign ClientSpring AOP 不适用于 Feign 客户端
【发布时间】:2019-01-25 14:43:34
【问题描述】:

我有一个 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 被调用。

但是当我在我的伪装层中添加这个注释(@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>

【问题讨论】:

  • 您可以尝试在您的@Configuration 类上添加@EnableAspectJAutoProxy 吗?

标签: spring aspectj spring-aop spring-cloud-feign


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-04-19
    • 2019-07-27
    • 2017-01-22
    • 2020-11-26
    • 2021-12-27
    • 1970-01-01
    • 2020-04-06
    • 2021-10-22
    • 2020-01-27
    相关资源
    最近更新 更多