Spring面向切面编程详解(4)

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class Test02 { @Autowired private CompactDisc compactDisc; @Test public void test02(){ compactDisc.playTrack(123); Encoreable compactDisc = (Encoreable) this.compactDisc; //当要调用添加的新功能的时候,这个用法相当于由代理转换到对应类实现,不会报类型转换错误 compactDisc.performEncode(); } }

View Code

 

三、使用XML声明切面

Spring面向切面编程详解

Spring面向切面编程详解

1、定义切面

 

public class AudienceXML { public void silenceCellPhones(){ System.out.println("Silencing cell phones"); } public void takeSeats(){ System.out.println("Taking seats"); } public void applause(){ System.out.println("CLAP CLAP CLAP!!!"); } public void demandRefund(){ System.out.println("Demanding a refund"); } }

View Code

2、XML配置切面

 

<aop:config> <aop:aspect ref="audienceXML"> <aop:pointcut id="performance" expression="execution(* com.service.Performance.perform(..))"/> <aop:before method="silenceCellPhones" pointcut-ref="performance"/> <aop:before method="takeSeats" pointcut-ref="performance"/> <aop:after-returning method="applause" pointcut-ref="performance"/> <aop:after-throwing method="demandRefund" pointcut-ref="performance"/> </aop:aspect> </aop:config>

View Code

3、创建环绕通知

 

public class Audience3XML { public void watchPerformance(ProceedingJoinPoint joinPoint) { System.out.println("Silencing cell phones"); System.out.println("Taking seats"); try { joinPoint.proceed(); System.out.println("CLAP CLAP CLAP!!!"); } catch (Throwable throwable) { System.out.println("Demanding a refund"); throwable.printStackTrace(); } } }

 

View Code

 

<aop:config> <aop:aspect ref="audience3XML"> <aop:pointcut id="performance3" expression="execution(* com.service.Performance.perform(..))"/> <aop:around method="watchPerformance" pointcut-ref="performance3"/> </aop:aspect> </aop:config>

View Code

4、匹配输入参数

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/9876fa0a01bbd57ccb32933e97052e8d.html