package com.denny_blue.springdemo.aop;
import java.util.HashSet;
import java.util.Set;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyAroundAdvice implements MethodInterceptor {
private Set customers=new HashSet(); //保存购过书的顾客信息
public Object invoke(MethodInvocation invocation) throws Throwable {
String customer=(String)invocation.getArguments()[0];
if(customers.contains(customer)){
throw new BuyBookException("对不起,一名顾客只能买一本打折书!");
}
Object result=invocation.proceed(); //调用MyBuyBook中的buyBook方法,即真实操作
customers.add(customer);
return result;
}
}
好了,最后一个,异常增强,当顾客要买< spring in action>时,我们的书店没书了,请仓库部门赶快订货!!
package com.denny_blue.springdemo.aop;
import org.springframework.aop.ThrowsAdvice;
public class MyThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(NoThisBookException e){ //可以定义多个方法,只要传入的参数是不同异常
System.out.print("通知仓库,赶紧加订书!");
}
}
好了没?还没,我们需要一个XML文件来组装这些对象,来代理业务接口,完整的beans.xml如下,各元素的含义请自己查看spring reference
?xml version="1.0" encoding="UTF-8"?>
< !DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
< beans>
< bean id="myBuyBookTarget" class="com.denny_blue.springdemo.aop.MyBuyBook"/>
< bean id="myBeforeAdvice" class="com.denny_blue.springdemo.aop.MyBeforeAdvice"/>
< bean id="myAroundAdvice" class="com.denny_blue.springdemo.aop.MyAroundAdvice"/>
< bean id="myAfterAdvice" class="com.denny_blue.springdemo.aop.MyAfterAdvice"/>
< bean id="myThrowsAdvice" class="com.denny_blue.springdemo.aop.MyThrowsAdvice"/>
< bean id="buyBook" class="org.springframework.aop.framework.ProxyFactoryBean">
< property name="proxyInterfaces">
文章来源于领测软件测试网 https://www.ltesting.net/