基于配置的spring AOP的一个示例

/**
*包括四个类,和一个配置文件
*1.切面类 Audience,此类中包括各种Advice,pointCut是对jointPoint的一个子集(通过表达式来获取)
*2和3: 接口Singer及其实现类SingerImpl,此类包括joinPoint 
*4.测试类Test
*配置文件:springtestconfiguration.xml
*/
package com.springinaction.aop.config;

public class Audience
{
	// 落座
	private void takeSeats()
	{
		System.out.println("落座");
	}

	// 关闭手机
	private void turnOffCellPhones()
	{
		System.out.println("关闭手机");
	}

	// 喝彩
	private void applaud()
	{
		System.out.println("喝彩");
	}

	// 退票
	private void demandRefund()
	{
		System.out.println("退票");
	}
}
/////////////////////////////
package com.springinaction.aop.config;

public interface Singer
{
	public void singSong();
}
///////////////////////////////
package com.springinaction.aop.config;

public class SingerImpl implements Singer
{
	private String song;

	public void setSong(String song)
	{
		this.song = song;
	}

	public void singSong()
	{
		System.out.println("我要唱: " + this.song);
	}
}
///////////////////////////
package com.springinaction.aop.config;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Test
{
	public static void main(String[] args)
	{
		//必须要使用上下文的applicationContext才能使用AOP,而bean工厂是不支持的
		//BeanFactory factory = new ClassPathXmlApplicationContext("springtestconfig.xml");
		BeanFactory factory = new FileSystemXmlApplicationContext("springtestconfig.xml");
		//BeanFactory factory = new XmlBeanFactory(new FileSystemResource("springtest.xml"));

		Singer singer = (Singer) factory.getBean("singer");
		singer.singSong();
	}
}
/////////////////////////////////

<?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"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
	<bean id="audience" class="com.springinaction.aop.config.Audience" />
	<bean id="singer" class="com.springinaction.aop.config.SingerImpl">
		<property name="song" value="爱你一万年" />
	</bean>

	<aop:config>
		<aop:aspect ref="audience">
			<aop:before method="takeSeats" pointcut="execution(* *.sing*(..))" />
			<aop:before method="turnOffCellPhones" pointcut="execution(* *.sing*(..))" />
			<aop:after-returning method="applaud"
				pointcut="execution(* *.sing*(..))" />
			<aop:after-throwing method="demandRefund"
				pointcut="execution(* *.sing*(..))" />
		</aop:aspect>
	</aop:config>
</beans>

你可能感兴趣的:(基于配置的spring AOP的一个示例)