<?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:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <bean id="boy" class="com.springboot.aop3.Boy"></bean> <bean id="girl" class="com.springboot.aop3.Girl"></bean> <bean id="buyAspectJ" class="com.springboot.aop3.BuyAspectJ"></bean> <aop:config proxy-target-class="true"> <aop:pointcut id="apoint" expression="execution(* com.springboot.aop3.IBuy.buy(..))"></aop:pointcut> <aop:aspect id="baj" ref="buyAspectJ"> <aop:before pointcut-ref="apoint" method="haha"></aop:before> <aop:after pointcut-ref="apoint" method="hehe"></aop:after> <aop:after-returning pointcut-ref="apoint" method="xixi"></aop:after-returning> <aop:around pointcut-ref="apoint" method="xxx"></aop:around> </aop:aspect> </aop:config> </beans>
[1]: <aop:pointcut>如果位于<aop:aspect>元素中,则命名切点只能被当前<aop:aspect>内定义的元素访问到.为了能被整个<aop:config>元素中定义的所有增强访问,必须在<aop:config>元素下定义切点.
[2]: 如果在<aop:config>元素下直接定义<aop:pointcut>,则必须保证<aop:pointcut>在,aop:aspect>之前定义.在<aop:conofig>下还可以定义<aop:advisor>,三者在<aop:config>中配置有先后顺序的要求:首先是<aop:pointcut>,
其次是<aop:advisor>,最后是<aop:aspect>.而在<aop:aspect>中定义的<aop:pointcut>则没有先后顺序的要求.可以在任何位置定义.
<aop:after-returning pointcut-ref="apoint" method="xixi" returning="retVal"></aop:after-returning>
public void afterReturning(int retVal) { }
[1]:returning属性必须和增强方法的入参名一致.(代码中绿色“retVal”)
<aop:after-throwing pointcut-ref="apoint" method="afteThrowingMethod" throwing="iae"></aop:after-throwing>
public void afteThrowingMethod(IllegalArgumentException iae) { }
[1]:通过throwing属性声明需要绑定的异常对象,指定的异常名必须和增强方法对应的入参名一致(代码中深绿色的“iae”)
<aop:before method="bindParam" pointcut="target(com.smart.NativeWaiter) and args(name,num,..)"></aop:before>
public void bindParam(int num,String name){}
[1]bingParam(int num,String name)和代码 args(name,num,..)声明的参数名必须相同.
<aop:config > <aop:advisor advice-ref="testAdvice" pointcut="point"/> </aop:config> <bean id="testAdvice" class="com.springboot.aop.TestBeforeAdvice"></bean>
各种切面类型混合使用,如图:
最后附加一张spring的4种切面定义的对比图片: