Aop
一、切面方法
# 前置通知(@Before ):目标方法之前之前执行
# 后置通知(@After ):目标方法执行之后一定会执行,不管是否发生异常
# 返回通知(@AfterReturning ):目标方法正常返回后执行
# 异常通知(@AfterThrowing ):目标方法抛出异常时执行
# 环绕通知(@Around ):动态代理,需要手动调用目标方法
二、示例
2.1 目标方法
public class Calculator {
public int div ( int i, int j) {
System. out. println ( "div execute..." ) ;
return i/ j;
}
}
2.2 切面类
@Aspect
public class LogAspects {
@Pointcut ( "execution(public int com.intellif.aop.Calculator.*(..))" )
public void myPointCut ( ) { } ;
@Before ( "myPointCut()" )
public void logStart ( JoinPoint joinPoint) {
System. out. println ( "@Before execute , Args:{" + Arrays. asList ( joinPoint. getArgs ( ) ) + "}" ) ;
}
@After ( "myPointCut()" )
public void logEnd ( JoinPoint joinPoint) {
System. out. println ( "@After execute finished ......" ) ;
}
@AfterReturning ( value = "myPointCut()" , returning = "result" )
public void logReturn ( Object result) {
System. out. println ( "@AfterReturning execute... Return successfully:{" + result + "}" ) ;
}
@AfterThrowing ( value = "myPointCut()" , throwing = "exception" )
public void logException ( Exception exception) {
System. out. println ( " @AfterThrowing execute .... Exception:{" + exception + "}" ) ;
}
@Around ( "myPointCut()" )
public Object around ( ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System. out. println ( "@Around:Before..." ) ;
Object obj = proceedingJoinPoint. proceed ( ) ;
System. out. println ( "@Around:After..." ) ;
return obj;
}
}
2.3 配置类
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
@Bean
public Calculator calculator ( ) {
return new Calculator ( ) ;
}
@Bean
public LogAspects logAspects ( ) {
return new LogAspects ( ) ;
}
}
2.4 测试
public class AopTest {
@Test
public void test01 ( ) {
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext ( AopConfig. class ) ;
Calculator c = app. getBean ( Calculator. class ) ;
int result = c. div ( 4 , 2 ) ;
System. out. println ( result) ;
app. close ( ) ;
}
}
2.5 输出
@Around : Before. . .
@Before execute , Args: { [ 4 , 2 ] }
div execute. . .
@Around : After. . .
@After execute finished . . . . . .
@AfterReturning execute. . . Return successfully: { 2 }
2
@Around : Before. . .
@Before execute , Args: { [ 4 , 0 ] }
div execute. . .
@After execute finished . . . . . .
@AfterThrowing execute . . . . Exception: { java. lang. ArithmeticException: / by zero}
java. lang. ArithmeticException: / by zero
2.6 小结
我们看到,正常情况下,Aop的切面方法执行顺序是:
@Around开始 ->@Before-> 目标方法 -> @Around完毕 -> @After ->@AfterReturning
@Around开始 ->@Before-> 目标方法 -> @After ->@AfterThrowing