美文网首页
Spring AOP之3w的配置

Spring AOP之3w的配置

作者: 一乐乐 | 来源:发表于2022-03-03 23:31 被阅读0次

1、3w是什么?

■ what、where、when 或者 what、when、where


2、what、where、when【通用】

(1)what:增强器-bean【配置一个bean对象】

(2)where:被增强的连接点-aop:pointcut【配置被增强的方法的属性-expression】

(3)when: 被增强的时机-aop:before/after-returning/after-throwing/after/around【前置、后置、异常、最终、环绕】

★ 3w 之间的关联:

■ where 和 when 同处在 元素aop:aspect 内部:

【where、when】整体-关联 what 是通过 元素aop:aspect 的属性 ref 关联是bean的增强器(what)

■ 内部的 when 和 where 之间:when 通过 pointcut-ref 关联到 where

    <!-- AOP 配置:what、where、when -->
    <!-- 1、what:做什么增强 -->
    <bean id="transactionManager" class="com.shan.tx.TransactionManager"/>
    
    <aop:config>
        <!-- 配置AOP切面 --> 
        <aop:aspect ref="transactionManager"> <!-- ✿ 关联what -->
            <!-- 2、where:在哪些包中的哪些类中的哪些方法上做增强 -->
            <aop:pointcut id="txPoint" expression="execution(* com.shan.service..*Service*.*(..))"/>
            <!-- 3、when:在方法执行的什么时机做增强 -->
            <aop:before method="open" pointcut-ref="txPoint"/>  <!-- ✿ 关联where -->
        </aop:aspect>
    </aop:config>



3、what、when、where【事务管理器特有】

(1)what:增强器-bean【配置一个bean对象】

(2)when: 被增强的时机(事务环绕增强特有)-tx:advice

(3)where:被增强的连接点-aop:pointcut【配置被增强的方法的属性-expression】

★ 3w 之间的关联:

■ when 和 what 之间:when 通过 (事务环绕增强特有)-tx:advice的属性 transaction-manager 关联是bean的增强器(what)

■ where 和 when 同处在 元素aop:config 内部:

通过元素aop:config的子元素aop:pointcut关联到where,然后又通过元素aop:config的子元素aop:advisor关联到when

    <!-- 1、what:配置jdbc事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 2:when:配置事务管理器增强(环绕增强) --><!-- ✿ 关联what -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="trans"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 3、where:配置切面 -->
    <aop:config>
        <aop:pointcut id="txPc" expression="execution(* com.shan.service.*Service.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/><!-- ✿ 关联when -->
    </aop:config>


写在后面的话

       如果你觉得一乐的文章给您带来了一些收获,可以给个三连❤️ ,一乐会一如既往地更新有价值的博客。如果文章存在错误,也欢迎大家指出。还有,如果大家有什么好的学习技巧、学习感悟,也非常欢迎大家在评论区一起交流~

最后感谢大家的支持,谢谢~

相关文章

网友评论

      本文标题:Spring AOP之3w的配置

      本文链接:https://www.haomeiwen.com/subject/bgkprrtx.html