一、注解创建切面
@Aspect: 表明该类为切面
@Before: 通知方法会在目标方法调用之前执行
@After: 通知方法会在目标方法返回或抛出异常后执行
@AfterReturning: 通知方法会在目标方法返回后执行
@AfterThrowing: 通知方法会在抛出异常后执行
@Around: 通知方法将目标方法封装起来
@Pointcut: 定义切点表达式
@EnableAspectJ-AutoProxy: 启用自动代理
execution(): 切点表达式
args(): 执行方法参数
with(): 指定匹配类型
public interface Performance{
public void perform();
public void playTrack(int i);
}
@Aspect
public class Audience{
@Pointcut("execution(** concert.Performance.perform(..))")
public void perform(){}
@Pointcut("execution(** concert.Performance.playTrack(int)) && args(trackNum)")
public void playTrack(int trackNum){}
@Before("perform()")
public void silenceCellPhones(){
System.out.println("Silencing cell phones");
}
@Before("playTrack(trackNum)")
public void playTrack(int trackNum){
System.out.println("trackNum");
}
@AfterReturning("perform()")
public void applause(){
System.out.println("CLAP CLAP CLAP");
}
@AfterThrowing("perform()")
public void demandRefund(){
System.out.println("Demanding a refund");
}
}
@Configuration
@EnableAspectJ-AutoProxy
@ComponentScan
public class ConcertConfig{
@Bean
public Audience audience(){
return new Audience();
}
}
二、XML声明切面
<aop:config>: 顶级AOP配置元素
<aop:aspect>: 定义一个切面
<aop:pointcut>: 定义一个切点
<aop:aspectj-autoproxy>: 启用自动代理
<aop:before>: AOP前置通知
<aop:after>: AOP后置通知(不管被执行方法是否执行成功)
<aop:after-returning>: AOP返回通知
<aop:after-throwing>: AOP异常通知
public interface Performance{
public void perform();
public void playTrack(int i);
}
public class Audience{
public void perform(){}
public void playTrack(int trackNum){}
public void silenceCellPhones(){
System.out.println("Silencing cell phones");
}
public void silenceCellPhones(int trackNum){
System.out.println("trackNum");
}
public void applause(){
System.out.println("CLAP CLAP CLAP");
}
public void demandRefund(){
System.out.println("Demanding a refund");
}
}
<aop:config>
<aop:aspect ref="audience">
<aop:pointcut
id="performance"
expression="execution(** concert.Performance.perform(..))" />
<aop:pointcut
id="trackCounter"
expression="execution(** concert.Performance.playTrack(int)) && args(trackNum)" />
<aop:before
pointcut-ref="performance"
method="silenceCellPhones" />
<aop:before
pointcut-ref="trackCounter"
method="playTrack" />
<aop:after-returning
pointcut-ref="performance"
method="applause" />
<aop:after-throwing
pointcut-ref="performance"
method="demandRefund" />
</aop:aspect>
</aop:config>