观众类Audience~~
[java]view plain copy packagecom.jCuckoo.demo;importorg.aspectj.lang.ProceedingJoinPoint;publicclassAudience{publicvoidtakeSeats(){System.out.println("----开演之前,请占座----");}publicvoidturnOffCellPhones(){System.out.println("----开始之前,请关机----");}publicvoidapplaud(){System.out.println("****鼓掌,继续鼓掌。****");}publicvoidturnOnCellPhones(){System.out.println("****演出结束,可以开机****");}publicvoiddemandRefund(){System.out.println(" 太熊了,退我票钱 ");}publicvoidwatchPerformance(ProceedingJoinPointjoinpoint){try{System.out.println("oooooooo环绕通知开始oooooooo");longstart=System.currentTimeMillis();joinpoint.proceed();longend=System.currentTimeMillis();System.out.println("oooooooo环绕通知结束oooooooo");System.out.println("演出耗时共计:"+(end-start)+"毫秒。");}catch(Throwablet){System.out.println("Boo!Wewantourmoneyback!");}}}
表演接口Performer
[java]view plain copy packagecom.jCuckoo.demo;publicinterfacePerformer{voidperform()throwsException;}
定义魔术师Juggler,实现表演接口
[java]view plain copy packagecom.jCuckoo.demo;publicclassJugglerimplementsPerformer{privateintbeanBags=3;publicJuggler(){}publicJuggler(intbeanBags){this.beanBags=beanBags;}publicvoidperform()throwsException{System.out.println("表演开始:魔术师欺骗了"+beanBags+"个游戏豆。");}}
spring的配置文档applicationContext.xml
[html]view plain copy <?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:aop="/schema/aop"xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.0.xsd/schema/tx/schema/tx/spring-tx-3.0.xsd/schema/aop/schema/aop/spring-aop-3.0.xsd"><beanid="juggler"class="com.jCuckoo.demo.Juggler"/><beanid="audience"class="com.jCuckoo.demo.Audience"/><aop:config><aop:aspectref="audience"><aop:pointcutid="performance"expression="execution(*com.jCuckoo.demo.Performer.perform(..))"/><aop:beforepointcut-ref="performance"method="takeSeats"/><aop:beforepointcut-ref="performance"method="turnOffCellPhones"/><aop:afterpointcut-ref="performance"method="turnOnCellPhones"/><aop:after-returningpointcut-ref="performance"method="applaud"/><aop:after-throwingpointcut-ref="performance"method="demandRefund"/><aop:aroundpointcut-ref="performance"method="watchPerformance"/></aop:aspect></aop:config></beans>
测试类,获取魔术师,并进行表演。
[java]view plain copy packagecom.jCuckoo.test;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importcom.jCuckoo.demo.Performer;publicclassMainTest{/***@paramargs*/publicstaticvoidmain(String[]args){ApplicationContextctx=newClassPathXmlApplicationContext("applicationContext.xml");Performerperformer=(Performer)ctx.getBean("juggler");try{performer.perform();}catch(Exceptione){e.printStackTrace();}}}
最终结果:
----开演之前,请占座---- ----开始之前,请关机---- oooooooo环绕通知开始oooooooo 表演开始:魔术师欺骗了3个游戏豆。 ****演出结束,可以开机**** ****鼓掌,继续鼓掌。**** oooooooo环绕通知结束oooooooo 演出耗时共计:1毫秒。