镜子的Sping 之旅 之AOP

AOP术语

通知(Advice):切面的工作。(什么和何时)

5种类型:Before,After,After-returning,After-throwing,Around。

连接点(Joinpoint):应用执行过程中能够插入切面的一个点(时机)。

切点(Pointcut):定义匹配通知织入的一个或多个连接点。(何处)

切面(Aspect):通知和切点的结合, 完成功能。

引入(Introduction):向现有类添加新方法或属性。

织入(Weaving):将切面应用到代理对象来创建新的代理对象的过程。

编译期(目标类编译时AspectJ),类加载期(LTW),运行期(Spring AOP)

编写切点

Spring借助AspectJ的切点表达式(一部分,用其他的会抛出IllegalArguementException)来定义切面。

execution(* com.company.example.Example.play(..))&& within(com.company.example)

*表示不关心方法返回值类型,execution()指示器选择Example的play()方法, play(..)表示不限定入参,&&操作符表示and关系, within()限制匹配,表示example下的任意类调用时。

Spring的bean()指示器可用BeanID或者名称限制切点,也可使用!bean()。

在XML中声明切面

前置或后置通知

例子:

<aop:config>
  <aop:aspect ref=””>(ref为需要调用的bean)
<aop:before pointcut = “execution(* ..(..))” method=””/> (method为ref类中的方法)
<aop:after pointcut=”expression(* ..(..))” method=””/>
  </aop:aspect>
</aop:config>

为避免重复定义冗余,可先定义

<aop:pointcut id=”id” expression=”execution()”/>
<aop:before pointcut-ref=”id” method=“”/>
<aop:after-throwing pointcut-ref=”id” method=””/>

环绕通知

需要在通知方法中加入ProceedingJoinPoint作为方法的入参,如果需要把控制转给被通知的方法可以调用ProceedingJoinPoint的proceed()方法。

声明方法没有太大区别,只是把aop:before换成aop:around。

为通知传参

在切点表达式中加入&& arg(参数),就可在<aop:before>等中加入 arg-names=”参数“调用。

通过切面引入(introduction)新功能

<aop:aspect>
<aop:declare-parents
       types-matching=”类型匹配路径”
       implement-interface=”实现接口路径”
       default-impl=”实现方法的bean路径” 或 delegate-ref=”bean id”
/>
<aop:aspect>

注解切面

在xml中更改配置

<aop:aspectj-autoproxy /> ;

在beans 中加入aop命名空间。

在类里 @Aspect 将任意类转化为切面;

@Pointcut 注解AspectJ切点表达式,下定义一个方法名,可供后续调用;

  @Pointcut(“execution(* ..)”)
  public void name(){}

@Before(“name()”)加方法;

@After @AfterReturning @AfterThrowing 使用方法同@Before

@Around(“name”)下方法中同样须使用ProcessingJoinPoint入参,并在对象中使用proceed()方法;

@DeclareParents(value=“”,default-impl=””)
 public static Interface interface;

value 等同于 type-matching,default-impl为接口实现,标注的static指定了被引入的接口。

注入AspectJ切面

可使用Spring的依赖注入将Bean装配入AspectJ切面中

<bean class=”” factory-method=”aspectOf”>
   <property name=”参数名” ref=”参数名”/>
</bean>
<bean id=”参数名” class=””>
   <peoperty name=”” …/>
</bean>

Spring 通过aspectOf()的工厂方法获得切面的引用然后像<bean>元素规定的那样依赖注入。

转载于:https://my.oschina.net/jingzigege/blog/729098

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值