2016-10-11 129 views
0

今天我試圖用Spring 4來管理一些AOP的東西,並且我有一個@Around註解的問題。它只能在切入點之後起作用,並像@After註釋那樣工作。更糟糕的是,組合@Before和@Around註釋僅在切入點後調用方法時纔會起作用。AOP,Spring 4 MVC和@Around註釋

組合@After和@Before工作正常。說實話 - 我不知道它爲什麼這樣工作。

我也嘗試了一些對的Mockito檢測調用AOP的方法,但它不工作。

我有配置類

@Configuration 
@EnableAspectJAutoProxy 
@ComponentScan(basePackages = { "my.package.to.aop" }) 
public class AOPConfiguration {} 

AOP類:

@Aspect 
@Component 
public class SmartLoggerAspect { 

    @After("execution(* my.package.to.specific.function." 
      + "repositories.PagingAndSortingBookRepository.findAll(" 
      + "org.springframework.data.domain.Pageable) )") 
    public void afterPage(JoinPoint joinPoint){ 
     System.out.println("\n\n\n\nCALLED AFTER: " + joinPoint.getSignature().getName()); 
    } 

    @Before("execution(* my.package.to.specific.function." 
      + "repositories.PagingAndSortingBookRepository.findAll(" 
      + "org.springframework.data.domain.Pageable) )") 
    public void beforePage(JoinPoint joinPoint){ 
     System.out.println("\n\n\n\nCALLED BEFORE: " + joinPoint.getSignature().getName()); 
    } 

    @Around("execution(* my.package.to.specific.function." 
      + "repositories.PagingAndSortingBookRepository.findAll(" 
      + "org.springframework.data.domain.Pageable) )") 
    public void aroundPage(JoinPoint joinPoint){ 
     System.out.println("\n\n\n\nCALLED AROUND: " + joinPoint.getSignature().getName()); 
    } 
} 

而且我做了一個單元測試它

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(classes = { JPAConfig.class, AOPConfiguration.class }) 
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class }) 
public class AspectTest { 

    @Autowired 
    PagingAndSortingBookRepository pagingAndSortingRepo; 
    @Autowired 
    SmartLoggerAspect smartLoggerAspect; 

    JoinPoint joinPoint; 


    @Test 
    public void pagingTest(){ 
     pagingAndSortingRepo.findAll(new PageRequest(1, 1)); 
     //verify(smartLoggerAspect, times(1)).afterPage(joinPoint); 
    } 
} 
+0

爲什麼你需要'@ Before' +'@ After' __and__'@ Around'建議嗎?你爲什麼不嘗試用一個'@ Around'的建議來梳理這些建議? –

+0

因爲我是初學者,並嘗試使用AOP的很多方法。當我評論aBefore和aAfter函數並且離開aAround時,我仍然遇到同樣的問題 –

+0

'你只能在切入點[...]'後才能使用? –

回答

0

我認爲這個問題是使用JoinPoint代替ProceedindJoinPointaround建議的方法。

還需要調用pjp.proceed法在各地的諮詢。

spring docs

通知方法的第一個參數引用必須是ProceedingJoinPoint類型。在通知的主體中,ProceedingJoinPoint調用proceed()會導致底層方法執行。

+0

否i編輯該功能 @Around( 「執行(* my.package.to.specific.function。」 \t \t \t + 「repositories.PagingAndSortingBookRepository.findAll(」 \t \t \t +「org.springframework.data ();}「) \t public void aroundPage(ProceedingJoinPoint proceedingJoinPoint)throws Throwable { \t \t proceedingJoinPoint.proceed(); System.out.println(「\ n \ n \ n \ n \ nCALLED AROUND:」+ proceedingJoinPoint.getSignature()。getName());}} \t} 而且仍然有同樣的問題 –