</pre><pre name="code" class="java">package com.entity;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class Audience {
//该注解用于定义一个可以在@Aspect切面可以重用的切点,将切点名称作为参数的值赋给了所有的通知注解
@Pointcut("execution(* com.Performer.perform(..))")
public void performance(){
}
@Before("performance()")
public void takeSeats(){
System.out.println("观众请入座!");
}
@Before("performance()")
public void turnOffCellPhones(){
System.out.println("入座后请关闭您的手机!");
}
@AfterReturning("performance()")
public void applaund(){
System.out.println("表演的很好,掌声!");
}
@AfterThrowing("performance()")
public void demandRefund(){
System.out.println("表演的太次了,要求返钱!");
}
//讲方法作为环绕通知作用于切点
<span style="white-space:pre"> </span>@Around("performance()")
public void watchPerformance(ProceedingJoinPoint joinPoint){
try{
System.out.println("观众请入座");
System.out.println("入座后请关闭您的手机!");
long start=System.currentTimeMillis();
//很重要,如果没有,将会阻止被通知的方法的调用
joinPoint.proceed();
for(int i=1;i<100000000;i++){
}
long end=System.currentTimeMillis();
System.out.println("表演的很好,掌声!");
System.out.println("这场表演一共花费:"+(end-start));
}catch(Throwable t){
System.out.println("下去!把我们的钱还给我们!");
}
}
}
(1)Audience类现在已经使用@AspectJ注解进行了标注,标明了Audience不仅是一个POJO还是一个切面
(2)@Pointcut注解:定义一个可以在@AspectJ切面可以重用的切点。该注解的值:是一个切点表达式--这里标示改切点必须匹配Performer的perform()方法。切点的名称源于注解所应用的方法名称
(3)@Before:标示前置通知方法
(4)@AfterReturning:标示后置通知方法
(5)@AfterThrowing:标示异常时通知方法
(6)@Around:方法作为环绕通知作用于切点
看一下我们的接口:Performer
package com;
import com.exception.PerformanceExcetion;
public interface Performer {
void perform() throws PerformanceExcetion;
}
接口的实现类:Juggler
package com.entity;
import com.Performer;
import com.exception.PerformanceExcetion;
public class Juggler implements Performer{
private int beanBags=3;
public Juggler(){
}
public Juggler (int beanBags){
this.beanBags=beanBags;
}
@Override
public void perform() throws PerformanceExcetion {
System.out.println("Juggler(杂技师) "+ beanBags +" beanBags ");
}
}
接下来我们需要在配置文件中注明:我们的Bean:
<bean id="audience" class="com.entity.Audience"/>
<bean id="juggler" class="com.entity.Juggler"></bean>
接口不需要声明Bean
最后一件事情:让Spring将Audience应用为一个切面,我们需要在Sping上下文中声明一个自动代理Bean,该Bean知道如何把@AspectJ注解所标注的Bean转为代理通知:
<aop:aspectj-autoproxy/>
测试用例:
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class springTest {
public static void main(String[] args) {
ApplicationContext cxt=new ClassPathXmlApplicationContext(
"classpath:/spring/spring.xml");
Performer performer=(Performer)cxt.getBean("juggler");
performer.perform();
}
}
输出结果:
观众请入座
入座后请关闭您的手机!
观众请入座!
入座后请关闭您的手机!
Juggler(杂技师) 3 beanBags
表演的很好,掌声!
这场表演一共花费:30
表演的很好,掌声!