看透Spring AOP
工作原因需要用到一个代理,首选Spring Aop ,很久没用了,今天翻了下文档看了下源码,发现看文档容易晕,看源码结构清晰明了,Advice,PointCut,Advisor泾渭分明,ProxyFactoryBean总控。
Target:主角,目的就是生成target的代理对象。
Advice:抛弃概念简单理解就是你要插入target的执行代码。
PointCut:就是你要在target文件的哪个方法哪个位置插入,之前还是之后。
Advisor:用来整合Advice与PointCut。
Spring Aop复杂在对于前四者再加上Interceptor的封装,对这四者的装饰封装衍生出了好多类,而实际上就是Proxy.newProxyInstance()罢了(对于非接口当然是耳熟能详的cglib),接下来用JDK动态代理来模拟一下,不想写那么多类了,就Advice植入Target吧,其他硬编码了。
advice接口及两个实现:
package cn.easyweb.aop;public class TestAOP {public static void main(String[] args) {EasyProxy proxy = new EasyProxy();Object obj = proxy.createProxy(new BeforeAdvice(new SimcardAssaign()));SourceAssaign assaign = (SourceAssaign) proxy.createProxy(new AfterAdvice(obj));assaign.assaign();}}