第一个AOP程序开发实例

    spring用过,但是没有系统的学习过,最近工作不是很忙,所以找了本书(SPRING实战)学习下,然后在这里也算做个笔记吧。
    一直都知道spring有两大宝:IOC和AOP。AOP在曾经做的项目中没有用到,所以一直不甚明白。这次机会让我可以一点点打开其神秘面纱
    下面开始介绍我的小程序了:
    定义Performer接口:
package com.study.spring.aop; 

public interface Performer { 
    public void perform(); 
}


    定义一个Performer的实现类Juggler:
package com.study.spring.aop;

public class Juggler implements Performer {	
	private int bagBeans = 3;	
	public Juggler() {}	
	public Juggler(int bagBeans) {
		this.bagBeans = bagBeans;
	}	
	public void perform() {
		System.out.println("perform" + bagBeans);
	}
}



    定义切面类
package com.study.spring.aop;

public class Audience {
	public void takeSeats() {
		System.out.println("The audience is taking their seats");
	}
	public void turnOffCellphones() {
		System.out.println("The audience is turning off their cellphones");
	}
	public void applaud() {
		System.out.println("CLAP CLAP CLAP CLAP CLAP CLAP ");
	}
	public void demandRefund() {
		System.out.println("Boo! We want our money back");
	}
}

     spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
           http://www.springframework.org/schema/aop
		   http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"
	xmlns:aop="http://www.springframework.org/schema/aop">

	<bean id="juggler" class="com.study.spring.aop.Juggler">
		<constructor-arg value="15" />
	</bean>

	<bean id="audience" class="com.study.spring.aop.Audience" />

	<aop:config>
		<aop:aspect ref="audience">
			<aop:pointcut id="performance"
				expression="execution(* com.study.spring.aop.Performer.perform(..))" />

			<aop:before pointcut-ref="performance" method="takeSeats" />
			<aop:before pointcut-ref="performance" method="turnOffCellphones" />
			<aop:after-returning pointcut-ref="performance"
				method="applaud" />
			<aop:after-throwing pointcut-ref="performance"
				method="demandRefund" />

		</aop:aspect>
	</aop:config>
</beans>


    定义测试类:
package com.study.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.study.spring.aop.Performer;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ctx = null;
		ctx = new ClassPathXmlApplicationContext("com/study/spring/spring.xml");
		Performer performer = (Performer) ctx.getBean("juggler");
		performer.perform();
	}

}


    执行结果:
The audience is taking their seats
The audience is turning off their cellphones
perform15
CLAP CLAP CLAP CLAP CLAP CLAP 

猜你喜欢

转载自jwhandsome521.iteye.com/blog/2239753