AOP

2020-01-20  本文已影响0人  茶酒qqq

AOP

spring的IOC基于反射,通过读取配置文件获取对象的全限定类名,然后用反射创建,相当于是把BeanFactory包装了,扩展了。

而spring的AOP是基于动态代理,把动态代理包装起来,我们通过xml配置AOP使用,减少重复代码,减少程序耦合,帮助维护。

AOP术语

学习Spring中AOP要明确的事

开发阶段(我们做的):

运行阶段(Spring框架完成的):

spring中基于XML的AOP配置步骤

  1. 把业务层Bean和通知Bean交给spring管理

    <bean id="accountService" class="com.chajiu.service.Impl.AccountService"></bean>
    
    <bean id="logger" class="com.chajiu.log.Logger"></bean>
    
  2. 使用aop:config标签表明开始AOP的配置

  3. 使用aop:aspect表明配置切面

    • id属性:给切面一个唯一标识
    • ref属性:标识指定的通知类Bean的id
  4. aop:aspect标签内部使用各种通知类型的标签配置通知的类型

    ​ 比如配置前置通知,使用:asp:before

    • method:用于指定通知类中的哪个方法是前置通知
    • pointcut:用于指定切入点表达式,也就是指定切入点是哪个类的哪个方法。
  5. aop:pointcut可以把切入点单独拿出来,使用id表示唯一名称,使用exception指定表达式

    <aop:config>
        <aop:pointcut id="p1" expression="execution(* com.chajiu.service.Impl.*.*(..) )"/>
        <aop:aspect id="logAdvice" ref="logger">
            <aop:before method="logSt" pointcut-ref="p1"></aop:before>
            <aop:after-returning method="logEd" pointcut-ref="p1"></aop:after-returning>
        </aop:aspect>
    
    </aop:config>
    

切入点表达式的写法:

上一篇下一篇

猜你喜欢

热点阅读