利用注解定义切面,必要配置自动代理功能
1、在XML中配置
<aop:aspectj-autoproxy/>
2、如果是在JavaConfig中,配置
@Configuration
@EnableAspectJAutoProxy
@ComponentScan
public class ConcerConfig{}
一、在POJO中定义前置和后置通知
@Aspect //定义切面
@Component //实例化该POJO,调用方法
public class Audience {
@Before("execution(* org.aop.Perform.play())")
public void silenceCellphone(){
System.out.println("please silence cell phone");
}
@Before("execution(* org.aop.Perform.play())")
public void takeSeates(){
System.out.println("please take Seate");
}
@Before("execution(* org.aop.Perform.play())")
public void applause(){
System.out.println("CLAP CLAP CLAP");
}
@Before("execution(* org.aop.Perform.play())")
public void demandRefund(){
System.out.println("Refund refund");
}
}
上面的切点定义可以优化:
@Aspect //定义切面
@Component //实例化该POJO,调用方法
public class Audience {
//方法内容不重要,本身只是一个标识,供@Pointcut注解依附
@Pointcut("execution(* org.aop.Perform.play())")
public void profPonit(){}
//直接引用该切点所依附的方法
@Before("profPonit()")
public void silenceCellphone(){
System.out.println("please silence cell phone");
}
@Before("profPonit()")
public void takeSeates(){
System.out.println("please take Seate");
}
@After("profPonit()")
public void applause(){
System.out.println("CLAP CLAP CLAP");
}
@After("profPonit()")
public void demandRefund(){
System.out.println("Refund refund");
}
}
AspectJ提供了五个注解来定义通知:
二、创建环绕通知
@Aspect
@Component
public class AroundAudience {
@Pointcut("execution(* org.aop.Performence.play())")
public void arounPoint(){}
@Around("arounPoint()")
public void watchPerformance(ProceedingJoinPoint jp){
try{
System.out.println("Silencing cell phones");
System.out.println("Taking seats");
jp.proceed();
System.out.println("CLAP CLAP CALP");
}catch (Throwable e){
System.out.println("Demanding a refund");
}
}
}
三、处理通知中的参数
@Pointcut("execution(* org.aop.Perform.palyTrace(int)) && args(Num)")
public void paraPoint(int Num){}
@Before("paraPoint(Num)")
public void countTrack(int Num){
Num++;
System.out.println("通知中 trackNum="+Num);
}
四、通过注解引入新功能
@Aspect
@Component
public class EncodeIntro {
@DeclareParents(value = "org.aop.Performence+",
defaultImpl = DefaultEncore.class)
public static Encorable encorable;
}
value属性指定了哪种类型的bean要引入该接口
defaultImpl 属性指定了为引入功能提实现的类
@DeclareParents注解所标注的静态属性指明了要引入的接口