springAop 面向切面编程,重要的是切点,多个点结合起来就是面,所以是切面,我个人是怎么理解的,有点受高中数学的影响,我们接下来说说一下三点
1.前置增强
2.后置增强
3.环绕增强
-
前置增强
是什么呢?就是我们之前的before() 方法
-
后置增强
同理就是,after()
3.环绕增强
不就是前后一套都来,不就是环绕增强了吗?对,是的,我们还是来看代码吧
//接口
public interface Hello { public void say(String name); }
//实现类 public class HelloImpl implements Hello { public void say(String name) { System.out.println(name); } }
//这个类 实现的before()就是springAop的前置增强,自然afterReturning就是后置增强咯,哈哈哈 public class SuperAdvice implements AfterReturningAdvice,MethodBeforeAdvice{ public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable { System.out.println("之后"); } public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println("之前"); } }
//测试
@Test public void a(){ ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new HelloImpl()); proxyFactory.addAdvice(new SuperAdvice()); Hello hello = (Hello) proxyFactory.getProxy(); hello.say("张三"); }
console:
之前
张三
之后
那么怎么实现环绕增强呢? 看代码
public class AroundAdvice implements MethodInterceptor{ public Object invoke(MethodInvocation methodInvocation) throws Throwable { System.out.println("之前"); Object result = methodInvocation.proceed(); System.out.println("之后"); return result; } }
MethodInterceptor并不是spring的接口,而是Aop联盟提出的强大接口,调用方式一样
public class TestA { @Test public void a(){ ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new HelloImpl()); proxyFactory.addAdvice(new AroundAdvice()); Hello hello = (Hello) proxyFactory.getProxy(); hello.say("张三"); } }
结果同上
console:
之前
张三
之后
下次继续说!