yuyee

AOP日记


  最近在学着总结,因为常感觉做完东西,长久不用,过段时间就忘,下次想复习下都不行。
 AOP,面向方面编程,我们系统中有很多组件组成,每一个组件负责一部分业务功能,
 但是这些组件往往又带有一部分核心功能外的附加功能,而且是重复代码,如:日志,安全,事务! 通过AOP,实现这些附加功能的可重复利用。
 
 AOP其实可以看作是代理模式的扩展,写一个简单的代理
 
public class ProxySubject implements ProxyInterface {
private Subject innerObj;// 真正的对象

@Override
public void handle() {
innerObj = new Subject();
// 做额外的事情
innerObj.handle();// 真正的处理业务
// 做额外的事情
}
}

 Aop中叫代理类为advice,可以有多个连接起来,一个事件链

  实现AOP,还需要涉及到JAVA的反射,通过反射,获取method对象,并执行方法,AOP规范包里有个接口

 

 

public interface MethodInterceptor extends Interceptor {

    

     *Implement this method to perform extra treatments before and

     * after the invocation. Polite implementations would certainly

     * like to invoke {@link Joinpoint#proceed()}.

     *

     * @param invocation the method invocation joinpoint

     * @return the result of the call to {@link

     * Joinpoint#proceed()}, might be intercepted by the

     * interceptor.

     *

     * @throws Throwable if the interceptors or the

     * target-object throws an exception.  

     Object invoke(MethodInvocation invocation) throws Throwable;

      }

      通过 MethodInvocation的 getMethod()获得方法对象,并执行

      这样,如果你一个类中有很多方法,就可以通过这么一个

      

      AOP中生成代理类有3种方式,

      1.静态编译时期,源代码生成,为每个符合条件的类生成一个代理类

      2.静态字节码增强通过ASM/CGLIB分析字节码,生成代理类

      3.动态字节码增强,spring aop就是这样,ASM/CGLIB或者JDK的动态代理

      AOP的原理可以理解为代理模式+放射+自动字节码生成

Spring中动态代理有2种方式,一种是通过CGLIB,一种是JDK。

什么时候采用JDK什么时候采用CGLIB动态生成,主要取决于你又没实现接口,JDK动态代理需要目标类实现某接口,而CGLIB则是生成目标类的子类

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {

if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {

Class targetClass = config.getTargetClass();

if (targetClass == null) {

throw new AopConfigException("TargetSource cannot determine target class: " +

"Either an interface or a target is required for proxy creation.");

}

if (targetClass.isInterface()) {

return new JdkDynamicAopProxy(config);

}

if (!cglibAvailable) {

throw new AopConfigException(

"Cannot proxy target class because CGLIB2 is not available. " +

"Add CGLIB to the class path or specify proxy interfaces.");

}

return CglibProxyFactory.createCglibProxy(config);

}

else {

return new JdkDynamicAopProxy(config);

}

}

这个是DefaultAopProxyFactory里创建代理类的方法


 

 

posted on 2010-10-24 23:48 羔羊 阅读(312) 评论(0)  编辑  收藏 所属分类: aop