package com.audience;
public void takeSeats() {
System.out.println("----表演马上开始,请先占位----");
}
public void turnOffCellPhones()
{
System.out.println("-----开始之前,请关机---");
}
public void applaud() {
System.out.println("----表演的不错,请鼓掌---");
}
public void turnOnCellPhones() {
System.out.println("---演出结束,可以开机---");
}
public void demandRefund() {
System.out.println("---表演的不好,退钱---");
}
public void watchPerformance(ProceedingJoinPoint joinPoint) {
try {
System.out.println("=====环绕开始=====");
long start=System.currentTimeMillis();
System.out.println("签名:"+joinPoint.getSignature());
joinPoint.proceed();
long end=System.currentTimeMillis();
System.out.println("共耗时="+(end-start)+"毫秒");
System.out.println("===环绕结束===");
} catch (Throwable e) {
System.out.println("切入失败");
e.printStackTrace();
}
}
}
2.目标方法的接口类(可以作为切点)
}
3.目标方法的实现类(也可以作为切点)
@Override
public void perform() {
System.out.println("----魔术师开始欺骗----");
}
}
4.配置文件
<?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-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<bean id="juggler" class="com.juggler.Juggler"/>
<bean id="audience" class="com.audience.Audience"/>
<aop:config>
<!-- 切点可以是目标方法的接口类,也可以是目标方法的实现接口类 -->
<aop:pointcut expression="execution(* com.juggler.Performer.perform())" id="performence"/>
<aop:aspect ref="audience">
<aop:before method="takeSeats" pointcut-ref="performence"/>
<aop:before method="turnOffCellPhones" pointcut-ref="performence"/>
<aop:around method="watchPerformance" pointcut-ref="performence"/>
<aop:after method="turnOnCellPhones" pointcut-ref="performence"/>
<aop:after-returning method="applaud" pointcut-ref="performence"/>
<aop:after-throwing method="demandRefund" pointcut-ref="performence"/>
</aop:aspect>
</aop:config>
</beans>
5.测试类
import javax.faces.application.Application;
import org.springframework.context.support.ClassPathXmlApplicationContext;
ApplicationContext context=new ClassPathXmlApplicationContext("config.xml");
//此时必须是接口类的对象
Performer performer=(Performer) context.getBean("juggler");
performer.perform();
}
}