利用SPring AOP配置切面的一个例子

来源:互联网 发布:淘宝搜索什么能看片 编辑:程序博客网 时间:2024/03/29 04:26

这个例子,就是对于DukePerformer类,在它的演奏方法perform执行前,输出观众找座位takeSeat和关手机turnOffPhone,在执行后,输出观众鼓掌applaud。

将代码提取出来,独立于一个模块中,就是切面编程。主要还是为了松散耦合。

首先定义DukePerformer类:

package com.XinXiangShop.AOP;public class DukePerformer implements Performer{private String name;public void setName(String name){this.name=name;}public String getName(){return this.name;}@Overridepublic void perform() {// TODO Auto-generated method stubSystem.out.println(this.name+" sing a song.");}}

然后定义观众类:

package com.XinXiangShop.AOP;public class Audience {public void takeSeat(){System.out.println("The audiences take seat.");}public void turnOffPhone(){System.out.println("The audiences turn off the phone.");}public void applaud(){System.out.println("CLAP CLAP CLAP...");}public void unHappy(){System.out.println("The audiences are unhappy.");}}

对于applilcationContext.xml的配置如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:aop="http://www.springframework.org/schema/aop"       xsi:schemaLocation="http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd           http://www.springframework.org/schema/aop           http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  <!-- AOP学习时的配置 -->  <bean id="DukePerformer" class="com.XinXiangShop.AOP.DukePerformer">  <property name="name" value="duke"/>  </bean>  <bean id="audience" class="com.XinXiangShop.AOP.Audience"/>  <aop:config>  <aop:aspect ref="audience">  <aop:before method="takeSeat" pointcut="execution(* *.perform(..))"/>  <aop:before method="turnOffPhone" pointcut="execution(* *.perform(..))"/>  <aop:after-returning method="applaud" pointcut="execution(* *.perform(..))"/>  <aop:after-throwing method="unHappy" pointcut="execution(* *.perform(..))"/>  </aop:aspect>  </aop:config>  <!-- AOP学习时的配置 --></beans>

测试的代码如下:

package com.XinXiangShop.AOP;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;public class Main {public static void main(String[] args){ApplicationContext ctx=new FileSystemXmlApplicationContext("src/com/XinXiangShop/AOP/applicationContext.xml");Performer per=(Performer)ctx.getBean("DukePerformer");per.perform();}}

如果在执行时报java.lang.NoClassDefFoundError: org/aspectj/weaver/BCException那么是缺少 aspectjweaver-1.5.3.jar

程序运行的结果为:

The audiences take seat.
The audiences turn off the phone.
duke sing a song.
CLAP CLAP CLAP...