chapter04_面向切面的Spring_4_使用Xml创建切面

  • 首先要在头部添加aop命名空间

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/aop
             http://www.springframework.org/schema/aop/spring-aop.xsd">
    
  • Xml和JavaConfig的对应关系

    <aop:aspectj-autoproxy> @EnableAspectJAutoProxy

    <aop:config> 顶层配置元素,绝大多数的<aop:xxx>都要套在这个元素下面

    <aop:aspect> @Aspect

    <aop:after> @Afer

    <aop:after-returning> @AfterReturning

    <aop:after-throwing> @AfterThrowing

    <aop:around> @Around

    <aop:before> @Before

  • 使用Xml配置,通知类无需添加任何注解(例如 @Aspect),只需要在xml中配置

  • 示例

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/aop
             http://www.springframework.org/schema/aop/spring-aop.xsd">
    
          <bean id="volunteer" class="com.springinaction.springidol.Volunteer"/>
    
          <bean id="magician" class="com.springinaction.springidol.Magician"/>
    
          <aop:config>
              <aop:aspect ref="magician">
    
              <aop:before method="interceptThoughts"
                   arg-names="thoughts, people"
                   pointcut="execution(* com.springinaction.springidol.Thinker.thinkOfSomething(String, String)) 
                   and args(thoughts, people)"/>
    
              </aop:aspect>
          </aop:config>
      </beans>
    

    说明

    (1) <aop:config>是定义切面的根元素,它也要嵌套进 <beans>下

    (2) 使用切面类,也要声明切面类的bean

    (3) <aop:aspect ref="magician">用于声明一个切面,ref用于指向切面类的id

    (4) 能够成为切面的类必须是具体的实现类,不能是接口

    (5) <aop:before>(其他4种通知时刻类型同理)包括了几种属性

    pointcut代表切点函数

    args代表方法参数名字(要匹配)

    method代表通知的方法

    arg-names代表通知方法的参数名字

    (6) 不同切点表达式之间用 and,or,not连接(JavaConfig使用 &&,||,!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值