通知类是spring面向切面编程的产物,其原理是动态代理的设计模式,动态代理设计模式不在此处展开讲。我们只需要知道到我们编写的advice类可以通过动态代理在其方法内部任意位置调用其它类的功能(也就是我们要增强的类)。所谓的前置后置其实就是增强代码在核心代码之前还是之后执行。
前置通知:MethodBeforeAdvice对于前置通知类的实现我们只需要继承MethodBeforeAdvice并重写before方法
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class MyAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("前置增强");
}
}
后置通知:AfterAdvice
一般不用这个类而是使用下面的AfterReturningAdvice。
后置通知:AfterReturningAdvice //有异常不执行,方法会因异常而结束,无返回值import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class MyAfter implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("后置增强");
}
}
异常通知:ThrowsAdvice
注意这个类中方法需要我们自己选择要实现的方法(也就是自己写不能直接ctrl+O了)
import org.springframework.aop.ThrowsAdvice;
public class MyThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(Exception e) throws Throwable{
System.out.println("出异常了..."+e);
}
}
环绕通知:MethodInterceptor
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyIntercept implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("环绕前");
Object res = methodInvocation.proceed();
System.out.println("环绕后");
return res;
}
}
spring中的配置



