Spring AOP之3w的配置
2022-03-06 17:57:41


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>

本文摘自 :https://www.cnblogs.com/


更多科技新闻 ......