Spring的AOP动态代理

6. AOP动态代理

AOP(Aspect Oriented Programming),即面向切面编程(也叫面向方面编程,面向方法编程)。其主要作用是,在不修改源代码的情况下给某个或者一组操作添加额外的功能。像日志记录,事务处理,权限控制等功能,都可以用AOP来“优雅”地实现,使这些额外功能和真正的业务逻辑分离开来,软件的结构将更加清晰。AOP是OOP的一个强有力的补充。

1. 注解

  • @Before – 目标方法执行前执行
  • @After – 目标方法执行后执行
  • @AfterReturning – 目标方法返回后执行,如果发生异常不执行
  • @AfterThrowing – 异常时执行
  • @Around – 在执行上面其他操作的同时也执行这个方法

Pointcut expression

Pointcut可以有下列方式来定义或者通过&& || 和!的方式进行组合.

  • args()
  • @args()
  • execution()
  • this()
  • target()
  • @target()
  • within()
  • @within()
  • @annotation 其中execution 是用的最多的,其格式为:

ret-type-pattern,name pattern, 和 parameters pattern是必须的.

ret-type-pattern:可以为表示任何返回值,全路径的类名等. name-pattern:指定方法名,代表所以,set,代表以set开头的所有方法. parameters pattern:指定方法参数(声明的类型),(..)代表所有参数,()代表一个参数,(*,String)代表第一个参数为任何值,第二个为String类型. 举例说明:

  1. 任意公共方法的执行: execution(public * *(..))
  2. 任何一个以“set”开始的方法的执行: execution(* set*(..))
  3. AccountService 接口的任意方法的执行:

execution(* com.xyz.service.AccountService.*(..))

  1. 定义在service包里的任意方法的执行:

execution(* com.xyz.service..(..))

  1. 定义在service包和所有子包里的任意类的任意方法的执行:

execution(* com.xyz.service...(..))

  1. 定义在pointcutexp包和所有子包里的JoinPointObjP2类的任意方法的执行:

execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))

  1. pointcutexp包里的任意类.

within(com.test.spring.aop.pointcutexp.*)

  1. pointcutexp包和所有子包里的任意类.

within(com.test.spring.aop.pointcutexp..*)

  1. 实现了Intf接口的所有类,如果Intf不是接口,限定Intf单个类.

this(com.test.spring.aop.pointcutexp.Intf)

  1. 带有@Transactional标注的所有类的任意方法.

@within(org.springframework.transaction.annotation.Transactional) @target(org.springframework.transaction.annotation.Transactional)

  1. 带有@Transactional标注的任意方法.

@annotation(org.springframework.transaction.annotation.Transactional)

  1. 参数带有@Transactional标注的方法. @args(org.springframework.transaction.annotation.Transactional)
  2. 参数为String类型(运行是决定)的方法. args(String)

2. SpringMVC如果要使用AOP注解,

<aop:aspectj-autoproxy proxy-target-class="true"/>

猜你喜欢

转载自blog.csdn.net/hejian708837/article/details/85129406
今日推荐