AOP原理及一些概念

要spring框架中,实现AOP的代理方法就是8、9两种方法,当目标对象业务bean有实现接口方法时,使用AOP代理,当业务Bean没有实现接口时,会合适CGLIB方法来创建代理对象。此过程的判断及调用及由spring框架来实现。
一些概念:http://blog.csdn.net/zhangjiawei520/article/details/7474923

AspectJ开发

(12)AspectJ开发
AspectJ是一个基于java语言的AOP框架,它提供了强大的AOP功能。spring2.0后引入AspectJ框架,使用Aspectj实现AOP的两种方式:
a. 基于AspectJ的xml配置
b. 基于AspectJ的注解方式

基于AspectJ的xml配置

AOP的准备工作
A 导入jar包,包括基本的jar包,和开发aop的jar包
spring的基础包,spring-aop包及以下各包
Spring学习(六)
B 导入aop的约束,在.xml中使用
编写目标对象
Spring学习(六)
编写切面
按照增强在目标类方法中的连接点位置,可以分为5种:

  1. 前置增强:org.springframework.aop.BeforeAdvice是前置增强顶层接口,因为Spring只支持方法的增强,其子接口MethodBeforeAdvice是目前可用的前置增强。表示在目标方法执行前实施增强。
  2. 后置增强:org.springframework.aop.AfterReturningAdvice是目前可用的后置增强,表示在目标方法执行后实施增强。
  3. 环绕增强:org.aopalliance.intercept.MethodInterceptor代表了环绕增强,表示在目标方法执行前后实施增强。直接使用了AOP联盟定义的接口。
  4. 异常抛出增强:org.springframework.aop.ThrowsAdvice代表了异常抛出增强,表示在目标方法抛出异常后实施增强。
  5. 引介增强:org.springframework.aop.IntroductionInterceptor代表引介增强,表示在目标类中添加一些新的方法和属性。
    Spring学习(六)
    配置xml
     其中 execution 是用的最多的,其格式为:
    execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?)
    returning type pattern,name pattern, and parameters pattern是必须的.
    ret-type-pattern:可以为表示任何返回值,全路径的类名等.
    name-pattern:指定方法名,代表所以,set,代表以set开头的所有方法.
    parameters pattern:指定方法参数(声明的类型),(…)代表所有参数,(
    )代表一个参数,(,String)代表第一个参数为任何值,第二个为String类型.
    举例说明:
    任意公共方法的执行:
    execution(public * (…))
    任何一个以“set”开始的方法的执行:
    execution(
    set
    (…))
    AccountService 接口的任意方法的执行:
    execution(* com.xyz.service.AccountService.(…))
    定义在service包里的任意方法的执行:
    execution(
    com.xyz.service..(…))
    定义在service包和所有子包里的任意类的任意方法的执行:
    execution(* com.xyz.service….(…))
    定义在pointcutexp包和所有子包里的JoinPointObjP2类的任意方法的执行:
    execution(* com.test.spring.aop.pointcutexp…JoinPointObjP2.*(…))")
    *> 最靠近(…)的为方法名,靠近.(…))的为类名或者接口名,如上例的JoinPointObjP2.(…))

Spring学习(六)
测试
Spring学习(六)
Spring学习(六)

相关文章: