首先在xml文件内配置上下文
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
然后注册业务BEAN
<bean id="bankService" class="springboot.aop.xml.BankServiceImpl">
</bean>
<!-- bankService为接口 class后为包名.接口实现类名-->
<bean id="loggerAspect" class="springboot.aop.xml.LoggerAspect"></bean>
<!-- LoggerAspect为类-->
首先使用aop:config标签 确定切面(拦截哪些对象的方法)
表达式:expression=“execution(* springboot.aop.xml..(…))”
第一个* 表示不限制返回值类型
第二个* 表示springboot.aop.xml包下所有的JAVA BEAN
第三个* javabean 所有的方法
(…) 表示对方法的参数没有限制
接着用aop:aspect标签 引入通知类
1.aop:before 前置通知 执行前会返回返回值
2.after method 后置通知 执行后会返回返回值
方法method="logerBefore"与method="logerAfter"皆为loggerPointCut中方法 并且方法参数必须为(JoinPoint jp)
3.后置返回通知 属性 returning 的值必须与 方法logerAfterReturning 返回值的返回值参数名保持一致 方法参数为(JoinPoint jp,Object returnValue)
4.环绕通知 方法参数: logerAround(ProceedingJoinPoint pjp) 可用来修改参数
5.aop:after-throwing 后置异常通知 参数为(JoinPoint jp,Exception exception) 有异常时exception才有值
<aop:config>
<aop:pointcut expression="execution(* springboot.aop.xml.BankServiceImpl.*(..))" id="loggerPointCut"/>
<aop:aspect ref="loggerAspect">
<aop:before method="logerBefore" pointcut-ref="loggerPointCut"/>
<aop:after method="logerAfter" pointcut-ref="loggerPointCut"/>
<aop:after-returning method="logerAfterReturning" pointcut-ref="loggerPointCut" returning="returnValue"/>
<aop:around method="logerAround" pointcut-ref="loggerPointCut"/>
<aop:after-throwing method="loggerAfterThrowing" pointcut-ref="loggerPointCut" throwing="exception"/>
</aop:aspect>
</aop:config>