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

这个例子,就是对于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;
	}
	@Override
	public void perform() {
		// TODO Auto-generated method stub
		System.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...

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值