2016-10-11 78 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} 而且仍然有同样的问题 –