今天我試圖用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);
}
}
爲什麼你需要'@ Before' +'@ After' __and__'@ Around'建議嗎?你爲什麼不嘗試用一個'@ Around'的建議來梳理這些建議? –
因爲我是初學者,並嘗試使用AOP的很多方法。當我評論aBefore和aAfter函數並且離開aAround時,我仍然遇到同樣的問題 –
'你只能在切入點[...]'後才能使用? –