spring中基于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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">

<!--配置spring的ioc,把service对象配置进来-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>

<!--配置Logger类-->
<bean id="logger" class="com.itheima.utils.Logger"></bean>

<!--配置aop-->
<aop:config>
<!--配置切入点表达式,id属性:用于指定表达式的唯一标识
expression属性用于z指定表达式内容
此标签写在aop:aspect标签内部只能用于当前切面显示
他可以写在aop:aspect外面,此时就变成了所有切面可用(且必须写在切面之前)-->
<aop:pointcut id="pt1" expression="execution(* *..*.*(..))"></aop:pointcut>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置前置对象:在切入点(业务层)方法执行之前执行-->
<aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>

<!--配置后置对象:在切入点(业务层)方法正常执行之后执行,和异常异常通知永远只能出现一个-->
<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>

<!--配置异常对象:在切入点方法执行产生异常之后执行-->
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>

<!--配置最终对象:无论切入点方法是否正常执行他都会在其后面执行-->
<aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>

<!--配置环绕通知
问题:
当我们配置了环绕通知后,切入点(service方法)方法没有执行,而通知方法执行了
分析:
通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的接入点方法,而我们的代码中没有
解决:
Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),
此方法就相当于明确调用切入点方法。该接口可以作为环绕通知的方法参数,在程序执行时,
spring框架会为我们提供该接口的实现类供我们使用
spring的环绕通知:
他是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式-->
<aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>
</aop:aspect>
</aop:config>
</beans>
posted @ 2020-02-08 19:48  lijiahaoAA  阅读(394)  评论(0编辑  收藏  举报