System.out.println("切入点方法执行完了 \n");
System.out.print(args[0] + "在");
System.out.print(target + "对象上被");
System.out.print(method + "方法删除了");
System.out.print("只留下:" + returnValue + "\n\n");
}
}
环绕通知:
View Code
/**
* 环绕通知
*
* @author yanbin
*
*/
public class BaseAroundAdvice implements MethodInterceptor {
/**
* invocation :连接点
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("===========进入around环绕方法!=========== \n");
// 调用目标方法之前执行的动作
System.out.println("调用方法之前: 执行!\n");
// 调用方法的参数
Object[] args = invocation.getArguments();
// 调用的方法
Method method = invocation.getMethod();
// 获取目标对象
Object target = invocation.getThis();
// 执行完方法的返回值:调用proceed()方法,就会触发切入点方法执行
Object returnValue = invocation.proceed();
System.out.println("===========结束进入around环绕方法!=========== \n");
System.out.println("输出:" + args[0] + ";" + method + ";" + target + ";" + returnValue + "\n");
System.out.println("调用方法结束:之后执行!\n");
return returnValue;
}
}
异常通知:
View Code
/**
* 异常通知,接口没有包含任何方法。通知方法自定义
*
* @author yanbin
*
*/
public class BaseAfterThrowsAdvice implements ThrowsAdvice {
/**
* 通知方法,需要按照这种格式书写
*
* @param method
* 可选:切入的方法
* @param args
* 可选:切入的方法的参数
* @param target
* 可选:目标对象
* @param throwable
* 必填 : 异常子类,出现这个异常类的子类,则会进入这个通知。
*/
public void afterThrowing(Method method, Object[] args, Object target, Throwable throwable) {
System.out.println("删除出错啦");
}
}
d、定义指定切点:
View Code
/**
* 定义一个切点,指定对应方法匹配。来供切面来针对方法进行处理
*
* 继承NameMatchMethodPointcut类,来用方法名匹配
*
* @author yanbin
*
*/
public class Pointcut extends NameMatchMethodPointcut {
private static final long serialVersionUID = 3990456017285944475L;
@SuppressWarnings("rawtypes")
@Override
public boolean matches(Method method, Class targetClass) {
// 设置单个方法匹配
this.setMappedName("delete");
// 设置多个方法匹配
String[] methods = { "delete", "modify" };
//也可以用“ * ” 来做匹配符号
// this.setMappedName("get*");
this.setMappedNames(methods);
return super.matches(method, targetClass);
}
}
e、配置:
View Code
< xml version="1.0" encoding="UTF-8" >
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-autowire="byName">