一、导入并加载jar包
AOP
aopalliance-1.0.jar
aspectjweaver-1.6.9.jar
spring-aop-3.2.13.RELEASE.jar
Spring
spring-beans-3.2.13.RELEASE.jar
spring-context-3.2.13.RELEASE.jar
spring-core-3.2.13.RELEASE.jar
spring-expression-3.2.13.RELEASE.jar
事务
spring-tx-3.2.13.RELEASE.jar
JDBC
mysql-connector-java-8.0.18.jar
二、编写切面类的增强的方法
1、增强类型:
-
前置增强 <aop:before ....> ,在目标方法执行之前执行
-
后置增强 <aop :after retuming ....> ,在目标方法正常执行(没有抛出异常)后执行
-
异常抛出 aop:after-throwing, 在目标方法抛出异常时执行
-
最终增强 <aop : after ...> 在目标方法执行完毕后执行(不论是否抛出异常)
-
环绕增强 <aop : around ...>,在目标方法执行前后都执行
三、在Spring的配置文件中注册
<aop:pointcut id="pointcut" expression="execution(public int add (com.spring.pojo.User))"/>
<aop:aspect ref="loggerAspect">
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut="execution(public int add (com.spring.pojo.User))"/>
<aop:after-returning method="afterRetuning" pointcut-ref="pointcut" returning="obj"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
<aop:around method="around" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
切入点表达式
public * 方法名(String) 匹配所有类型的返回值
public * 方法名(..) 匹配所有类型的返回值和参数
.com.spring.service.userService.(..) 匹配service.userService类中的所有方法
.com.spring.service...*(..) 匹配service包中的所有类中的所有方法