spring中AOP中配置切面和切入点(15)

2016/1/18 10:46:21


1.配置

Spring所有的切面和通知器都必须放在一个内(可以配置包含多个元素),每一个可以包含pointcut,advisor和aspect元素
(它们必须按照这个顺序进行相应的声明)

2.aspect配置

<bean id="zjxAspect" class="com.zjx.aspect.ZjxAspect"></bean>

<bean id="zjxAspectBiz" class="com.zjx.aspect.ZjxAspectBiz"></bean>

<aop:config>
    <!-- 这个声明了一个切面类 -->
    <aop:aspect id="zjxAspectAOP" ref="zjxAspect"></aop:aspect>
</aop:config>

3.pointcut配置

  • execution(public**(..)) 切入点为执行所有public方法时
  • execution(set(..))切入点为执行所有set方法开始的方法时
  • execution(com.xyz.service.AccountService.(..))切入点为执行AccountService类中的所有方法时
  • execution(*com.xyz.service..(..)) 切入点为执行com.xyz.service包下的所有方法时
  • execution(*com.xyz.service…(..)) 切入点为执行com.xyz.service包及其子包下的所有方法时

以下只有Spring中才能用,还有很多配置,可以查阅spring的官方文档

  • within(com.xyz.service.*)
  • within(com.xyz.service..*)within用于匹配制定类型内的方法执行
  • this(com.xyz.service.AccountService) this用于匹配当前AOP代理对象类型的执行方法
  • taget用于匹配当前目标对象类型的执行方法

配置

<bean id="zjxAspect" class="com.zjx.aspect.ZjxAspect"></bean>

<bean id="zjxAspectBiz" class="com.zjx.aspect.ZjxAspectBiz"></bean>

<aop:config>
    <aop:aspect id="zjxAspectAOP" ref="zjxAspect">
        <aop:pointcut expression="excution(com.zjx.aspect.*Biz*(..))" id="zjxPointcut"/>
    </aop:aspect>
</aop:config>

4.通知的配置

例如,在切入点之前织入before方法

<bean id="zjxAspect" class="com.zjx.aspect.ZjxAspect"></bean>

<bean id="zjxAspectBiz" class="com.zjx.aspect.ZjxAspectBiz"></bean>

<aop:config>
    <aop:aspect id="zjxAspectAOP" ref="zjxAspect">
        <aop:pointcut expression="excution(com.zjx.aspect.*Biz*(..))" id="zjxPointcut"/>
        <aop:before method="before" pointcut-ref="zjxPointcut"/>
    </aop:aspect>
</aop:config>

其余的通知可以参考该配置

5.Introduction

  • 简介允许一个切面声明一个实现指定接口的通知对象,并且提供了一个接口实现类来代表这些对象
  • 由中的元素声明该元素用于声明所匹配的类型拥有一个新的parent

6.advisor

  • advisor就像一个小的自包含的方面,只有一个advice
  • 切面自身通过一个bean表示,并且必须实现某个advice接口,同时,advice也可以很好的利用AspectJ的切入点表达式
  • Spring通过配置文件中元素支持advisor实际使用中,大多数情况下他会和transactional advice配合使用
  • 为了定义一个advisor的优先级以便让advice可以有序,可以使用order属性来定义advisor顺序
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章