package com.denny_blue.springdemo.aop;
public class BuyBookException extends RuntimeException {
public BuyBookException(String msg){
super(msg);
System.out.println(msg);
}
}
OK,接下来就是各类增强了,前增强,在业务方法buyBook之前调用,显示欢迎信息:
package com.denny_blue.springdemo.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyBeforeAdvice implements MethodBeforeAdvice {
public void before(Method arg0, Object[] arg1, Object target)
throws Throwable {
String customer=(String)arg1[0]; //第2个参数组就是被增强的方法传入的参数,本例中即customer,book
System.out.println("欢迎光临!"+customer+"!"); //显示欢迎信息!,在buyBook方法前调用
}
}
然后是后增强,当顾客已经买了书之后,显示欢送信息:
package com.denny_blue.springdemo.aop;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class MyAfterAdvice implements AfterReturningAdvice {
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
String customer=(String)arg2[0]; //同前增强一样,参数组3为传入参数,具体见spring doc
System.out.println("欢迎下次再来!"+customer+"!"); //显示欢送信息!
}
}
OK,有了上面两个advice我们就能提供给顾客很好的服务态度了,等等?我们还有规则没实现,不是说一名顾客只能买一本书吗?OK,我们用环绕增强来解决,在环绕增强中保存一个HashSet,判断顾客是否来过,来过就抛出一个异常,没来过再放入此Set中:
文章来源于领测软件测试网 https://www.ltesting.net/