简体   繁体   中英

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

I am new to 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. Or am I missing something?

Internal calls cannot be intercepted using 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. For JDK proxies, only public interface method calls on the proxy can be intercepted. With CGLIB, public and protected method calls on the proxy are intercepted (and even package-visible methods, if necessary). However, common interactions through proxies should always be designed through public signatures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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