2013-02-26 69 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。

相關問題