spring – 带注释的PRIVATE方法的AspectJ切入点

我想为使用特定注释注释的私有方法创建一个Pointcut.但是,当注释位于如下所示的私有方法时,不会触发我的方面.

@Aspect
public class ServiceValidatorAspect {
    @Pointcut("within(@com.example.ValidatorMethod *)")
    public void methodsAnnotatedWithValidated() {
}

@AfterReturning(
            pointcut = "methodsAnnotatedWithValidated()",
            returning = "result")
    public void throwExceptionIfErrorExists(JoinPoint joinPoint, Object result) {
         ...
}

服务接口

public interface UserService {

    UserDto createUser(UserDto userDto);
}

服务实施

    public class UserServiceImpl implements UserService {

       public UserDto createUser(UserDto userDto) {

             validateUser(userDto);

             userDao.create(userDto);
       }

       @ValidatorMethod
       private validateUser(UserDto userDto) {

            // code here
       }

但是,如果我将注释移动到公共接口方法实现createUser,则会触发我的方面.我应该如何定义切入点或配置我的方面以使我的原始用例工作?

最佳答案
8. Aspect Oriented Programming with Spring

Due to the proxy-based nature of Spring’s AOP framework, protected methods are by definition not intercepted, neither for JDK proxies (where this isn’t applicable) nor for CGLIB proxies (where this is technically possible but not recommendable for AOP purposes). As a consequence, any given pointcut will be matched against public methods only!

If your interception needs include protected/private methods or even constructors, consider the use of Spring-driven native AspectJ weaving instead of Spring’s proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving first before making a decision.

转载注明原文:spring – 带注释的PRIVATE方法的AspectJ切入点 - 代码日志