简体   繁体   English

在某些情况下,带有@annotation(...) 的 Spring AOP 似乎不起作用

[英]Spring AOP with @annotation(…) seems not to work in some cases

I am new to Spring AOP.我是 Spring AOP 的新手。 I implemented an aspect that is working just fine on one of my methods.我实现了一个在我的一种方法上运行良好的方面。 But when I refactor the method and pull out some of the logic (including the annotation which I use to trigger the aspect) then the aspect is not called any more.但是当我重构方法并提取一些逻辑(包括我用来触发方面的注释)时,就不再调用方面了。 More details are provided below.下面提供了更多详细信息。

I have something similar to this:我有类似的东西:

@RequiresCheck
public ServiceResult<AccountDto> save(AccountDto accountDto) {
    // some logic here
    accountRepository.save(account.toAccount());
    // some logic there
    return ServiceResult.ok(accountDto);
}

And an aspect that looks similar to this还有一个与此相似的方面

@Around("@annotation(requiresCheck)")
public Object checkFullSemRights(ProceedingJoinPoint joinPoint) throws Throwable {
    if (check()) {
        return joinPoint.proceed();
    }
    throw new Exception();
}

This code works just fine: When I refactor the first method to look like this:这段代码工作得很好:当我重构第一个方法看起来像这样:

public ServiceResult<AccountDto> save(AccountDto accountDto) {
    // some logic here
    return save2(accountDto.toAccount());
}

@RequiresCheck
public ServiceResult<AccountDto> save2(Account account) {
    accountRepository.save(account);
    // some logic there
    return ServiceResult.ok(account.toAccountDto());
}

Then the aspect is not executed anymore.然后不再执行方面。 I thought that the aspect should get executed for any method that has the annotation "@ResuiresCheck", but that seems not to be true.我认为应该为任何具有注释“@ResuiresCheck”的方法执行方面,但这似乎不是真的。 Or am I missing something?还是我错过了什么?

Internal calls cannot be intercepted using Spring AOP.使用 Spring AOP 无法拦截内部调用。

Relevant information from the documentation 文档中的相关信息

Due to the proxy-based nature of Spring's AOP framework, calls within the target object are, by definition, not intercepted.由于 Spring 的 AOP 框架基于代理的性质,根据定义,目标 object 内的调用不会被拦截。 For JDK proxies, only public interface method calls on the proxy can be intercepted.对于 JDK 代理,只能拦截代理上的公共接口方法调用。 With CGLIB, public and protected method calls on the proxy are intercepted (and even package-visible methods, if necessary).使用 CGLIB,代理上的公共和受保护的方法调用被拦截(如果需要,甚至包可见的方法)。 However, common interactions through proxies should always be designed through public signatures.但是,通过代理的常见交互应始终通过公共签名进行设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM