spring中的AOP

来源:互联网 发布:虚拟现实java培训 编辑:程序博客网 时间:2024/05/20 06:26

写于: 2009-04-06 12:07 自己的博客转移。

http://www.blogjava.net/lsbwahaha/archive/2009/04/06/264091.html

Spring 对AOP的支持(采用Annotation的方式)
1.spring依赖库
*SPRING_HOME/dist/spring.jar
*SPRING_HOME/lib/Jakarta-commons/commons-logging.jar
*SPRING_HOME/lib/log4j/log4j-1.2.14.jar
*SPRING_HOME/lib/aspectj/*.jar
2.采用Aspect定义切面
3.在Aspect定义Pointcut和Advice
4.启用AspectJ对Annotation的支持并且将Aspect类和目标对象配置到Ioc容器中


注意:在这种方法定义中,切入点的方法是不被执行的,它存在的目的仅仅是为了重用切入点  即Advice中通过方法名引用这个切入点

AOP:
     Cross cutting concern
      Aspect
      Advice
      Pointcut
      Joinpoint
      Weave
     Target Object
      Proxy
     Introduction

Spring 对AOP的支持(采用配置文件的方式)

1.spring依赖库
*SPRING_HOME/dist/spring.jar
*SPRING_HOME/lib/Jakarta-commons/commons-logging.jar
*SPRING_HOME/lib/log4j/log4j-1.2.14.jar
*SPRING_HOME/lib/aspectj/*.jar

2.配置如下:
<aop:config>
    <aop:aspect id="security" ref="securityHandler">
        <aop:pointcut id="allAddMethod" expression="execution(* com.lsb.spring.UserManagerImpl.add*(..))"/>
        <aop:before method="checkSecurity" pointcut-ref="allAddMethod" />
    </aop:aspect>
    </aop:config>

 
Spring 对AOP的支持(JoinPoint参数介绍)
Aspect默认情况不用实现接口,但对于目标对象(UserManagerImpl.java),在默认情况下必须实现接口, 如果没有实现接口必须引入CGLIB库
我们可以通过Advice中添加一个JoinPoint参数,这个值会由spring自动传入,从JoinPoint中可以取得参数值、方法名等等

 
Spring 对AOP的支持
1.如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP
2.如果目标对象实现了接口,可以强制使用CGLIB实现AOP
3.如果目标对象没有实现了接口,必须采用CGLIB库,spring会在JDK动态代理和CGLIB之间转换

如何强制使用CGLIB实现AOP?
*添加CGLIB库,SPRING_HOME/lib/cglib/*.jar
*在spring配置文件中加入<aop:aspectj-autoproxy proxy-target-class="true"/>

 
JDK动态代理和CGLIB字节码生成的区别?
*JDK动态代理只能对实现了接口的类生成代理,而不能针对类
*CGLIB是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法,因为是继承,所以该类最好不要申明成final


原创粉丝点击