2013-02-26 522 views
5

我想为使用特定注释注释的私有方法创建一个切入点。然而,当注解位于像下面这样的私有方法时,我的方面不会被触发。注释私有方法的AspectJ切入点

@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,我的方面被触发。我应该如何定义我的切入点或配置我的方面以使我的原始用例起作用?

回答

20

8. Aspect Oriented Programming with Spring

由于Spring的AOP框架的基于代理的性质,保护的方法是通过定义不拦截,既不是JDK代理(其中,这是不适用),也不是CGLIB代理(其中本技术上可行但不推荐用于AOP目的)。因此,任何给定的切入点将仅与公共方法匹配!

如果您的拦截需求包括protected/private方法或构造函数,请考虑使用Spring驱动的本机AspectJ编织,而不是Spring的基于代理的AOP框架。这构成了具有不同特征的AOP使用的不同模式,所以在作出决定之前一定要先熟悉编织。

+0

有没有这方面的例子可以指向?谢谢! – 2018-02-08 01:02:34

1

切换到AspectJ并使用特权方面。或者改变你的应用程序的设计,以适应Spring AOP的限制。我的选择将是更强大的AspectJ。