/**
*包括四个类,和一个配置文件
*1.切面类 Audience,此类中包括各种Advice,pointCut是对jointPoint的一个子集(通过表达式来获取)
*2和3: 接口Singer及其实现类SingerImpl,此类包括joinPoint
*4.测试类Test
*配置文件:springtestannotaion.xml
*/
package com.springinaction.aop.annotation;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class Audience
{
@Pointcut("execution(* sing*(..)) || execution(* del*(..))")
private void singMethodPointCut(){};
// 落座
@Before("singMethodPointCut()")
private void takeSeats()
{
System.out.println("落座");
}
// 关闭手机
@Before("singMethodPointCut()")
private void turnOffCellPhones()
{
System.out.println("关闭手机");
}
// 喝彩
@AfterReturning("singMethodPointCut()")
private void applaud()
{
System.out.println("喝彩");
}
// 退票
@AfterThrowing("singMethodPointCut()")
private void demandRefund()
{
System.out.println("退票");
}
}
/
package com.springinaction.aop.annotation;
public interface Singer
{
public void singSong();
}
///
package com.springinaction.aop.annotation;
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.annotation;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test
{
public static void main(String[] args)
{
//必须要使用上下文的applicationContext才能使用AOP,而bean工厂是不支持的
BeanFactory factory = new ClassPathXmlApplicationContext("springtestannotaion.xml");
//BeanFactory factory = new ClassPathXmlApplicationContext("springtestannotaion.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">
<aop:aspectj-autoproxy />
<bean id="audience" class="com.springinaction.aop.annotation.Audience" />
<bean id="singer" class="com.springinaction.aop.annotation.SingerImpl">
<property name="song" value="爱你一万年" />
</bean>
</beans>