一、AOP
1.概念
AOP:全称 Aspect Oriented Programming,即:面向切面编程。 AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。 把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。
AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码 经典应用:事务管理、性能监视、安全检查、缓存 、日志等
2.作用及优势
在程序运行期间,不修改源码对已有方法进行增强
3.实现方式
aop底层将采用代理机制进行实现。
- 接口 + 实现类:spring采用 jdk 的动态代理Proxy。
- 实现类:spring 采用 cglib字节码增强。
4.AOP相关概念
①Joinpoint( 连接点): 被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的连接点。
②Pointcut( 切入点): 要对哪些 Joinpoint 进行拦截,即被增强的连接点。
③Advice( 通知/ 增强): 拦截到 Joinpoint 之后所要做的事情,及增强代码。 通知的类型:
- 前置通知
org.springframework.aop.MethodBeforeAdvice:在目标方法执行前实施增强 - 后置通知
org.springframework.aop.AfterReturningAdvice:在目标方法执行后实施增强 - 异常通知
org.springframework.aop.ThrowsAdvice: 在方法抛出异常后实施增强 - 最终通知
org.springframework.aop.AfterAdvice:无论切入点方法是否执行,都会在其后执行 - 环绕通知
org.aopalliance.intercept.MethodInterceptor: 在目标方法执行前后实施增强 - 引介通知
org.springframework.aop.IntroductionInterceptor:在目标类中添加一些新的方法和属性

④Introduction(引介): 引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方 法或 Field。
⑤Target(目标对象): 目标类,需要被代理的类
⑥Weaving(织入): 是指把增强应用到目标对象来创建新的代理对象的过程。 spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。
⑦Proxy(代理): 代理类,一个类被 AOP 织入增强后,就产生一个结果代理类。
⑧Aspect( 切面): 是切入点和通知(引介)的结合。
二、基于xml的AOP配置
AccountService:
java
复制代码
public interface AccountService { void saveAccount(); void updateAccount(int accountId); int deleteAccount(); }
AccountServiceImpl:
java
复制代码
public class AccountServiceImpl implements AccountService{ public void saveAccount() { System.out.println("保存账户"); } public void updateAccount(int accountId) { System.out.println("更新账户"); } public int deleteAccount() { System.out.println("删除账户"); return 0; } }
LoggerUtil:
java
复制代码
public class LoggerUtil { public void printLog(){ System.out.println("printLog方法执行"); } }
beans.xml:
xml
复制代码
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 告知 spring 创建容器时要扫描的包 --> <!--<context:component-scan base-package="com.hcx"></context:component-scan>--> <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"> <constructor-arg name="ds" ref="dataSource"></constructor-arg> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springdemo"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> </bean> <!--要增强的类--> <bean id="accountService" class="com.hcx.service.impl.AccountServiceImpl"></bean> <!--通知类--> <bean id="loggerUtil" class="com.hcx.utils.LoggerUtil"></bean> <!--配置AOP--> <aop:config> <!--配置切面 --> <aop:aspect id="loggerAdvice" ref="loggerUtil"> <!-- 配置通知的类型,并且建立通知方法和切入点方法的关联--> <!--只对com.hcx.service.impl.AccountServiceImpl下的saveAccount()方法增强--> <aop:before method="printLog" pointcut="execution(public void com.hcx.service.impl.AccountServiceImpl.saveAccount())"></aop:before> <!--省略访问修饰符--> <aop:before method="printLog" pointcut="execution(void com.hcx.service.impl.AccountServiceImpl.saveAccount())"></aop:before> <!--返回值使用通配符:表示任意返回值--> <aop:before method="printLog" pointcut="execution(* com.hcx.service.impl.AccountServiceImpl.saveAccount())"></aop:before> <!--包名使用通配符表示任意包,有几级包写几个*--> <aop:before method="printLog" pointcut="execution(* *.*.*.*.AccountServiceImpl.saveAccount())"></aop:before> <!--包名使用..表示当前包及其子包--> <aop:before method="printLog" pointcut="execution(* *..AccountServiceImpl.saveAccount())"></aop:before> <!--类名使用通配符--> <aop:before method="printLog" pointcut="execution(* *..*.saveAccount())"></aop:before> <!--方法名使用通配符--> <aop:before method="printLog" pointcut="execution(* *..*.*())"></aop:before> <!--全通配--> <aop:before method="printLog" pointcut="execution(* *..*.*(..))"></aop:before> <!--指定int类型参数的执行--> <aop:before method="printLog" pointcut="execution(* *..*.*(int))"></aop:before> <!--使用通配符表示任意类型参数(需要有参数)--> <aop:before method="printLog" pointcut="execution(* *..*.*(*))"></aop:before> <!--..有无参数均可--> <aop:before method="printLog" pointcut="execution(* *..*.*(..))"></aop:before> </aop:aspect> </aop:config> </beans>
AOPTest:
java
复制代码
public class AOPTest { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); AccountService accountService = (AccountService)applicationContext.getBean("accountService"); accountService.saveAccount(); accountService.updateAccount(1); accountService.deleteAccount(); } }
AOP配置:
- 使用
aop:config标签表明开始AOP的配置 - 使用
aop:aspect标签表明配置切面 id属性:是给切面提供一个唯一标识 ref属性:是指定通知类bean的Id。 - 在aop:aspect标签的内部使用对应标签来配置通知的类型 示例是让printLog方法在切入点方法执行之前执行:为前置通知: aop:before:表示配置前置通知 method属性:指定LoggerUtil类中哪个方法是前置通知(即增强的代码) pointcut属性:指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
切入点表达式: 关键字:execution(表达式) 表达式:访问修饰符 返回值 包名.包名.包名...类名.方法名(参数列表)
- 标准的表达式写法:
public void com.hcx.service.impl.AccountServiceImpl.saveAccount() - 省略访问修饰符:
void com.hcx.service.impl.AccountServiceImpl.saveAccount() - 返回值使用通配符:表示任意返回值:
* com.hcx.service.impl.AccountServiceImpl.saveAccount() - 包名使用通配符:表示任意包。有几级包,就需要写几个:*
* *.*.*.*.AccountServiceImpl.saveAccount()) - 包名使用..表示当前包及其子包:
* *..AccountServiceImpl.saveAccount() - 类名和方法名使用*来实现通配:
* *..*.*()
参数列表:
- 直接写数据类型: 基本类型直接写名称:
int引用类型写包名.类名的方式java.lang.String - 使用通配符表示任意类型,但是必须有参数
- 使用..表示有无参数均可,有参数可以是任意类型
- 全通配写法:
* *..*.*(..)
实际开发中切入点表达式的通常写法:切到业务层实现类下的所有方法:* com.hcx.service.impl.*.*(..)
通知类型:
环绕通知:可以在代码中手动控制增强方法何时执行。 ProceedingJoinPoint接口中的proceed()方法可以调用切入点方法,该接口可以作为环绕通知的方法参数。
LoggerUtil:
java
复制代码
package com.hcx.utils; import org.aspectj.lang.ProceedingJoinPoint; /** * Created by hongcaixia on 2019/12/17. */ public class LoggerUtil { /** * 前置 */ public void methodBeforeAdvice(){ System.out.println("前置通知"); } /** * 后置 */ public void afterReturningAdvice(){ System.out.println("后置通知"); } /** * 异常 */ public void throwsAdvice(){ System.out.println("异常通知"); } /** * 最终 */ public void afterAdvice(){ System.out.println("最终通知"); } /** * 环绕 */ public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){ try { Object[] args = proceedingJoinPoint.getArgs(); //前置通知:proceed方法之前 System.out.println("环绕通知"); //调用切入点方法 Object proceed = proceedingJoinPoint.proceed(args); //后置通知:proceed方法之后 System.out.println("环绕通知"); return proceed; } catch (Throwable throwable) { //异常通知 System.out.println("环绕通知"); throwable.printStackTrace(); }finally{ System.out.println("环绕通知"); } return null; } /** * 引介 */ public void introductionInterceptor(){ System.out.println("引介通知"); } }
beans.xml:
xml
复制代码
<!--配置AOP--> <aop:config> <aop:pointcut id="pointcut" expression="execution(* com.hcx.service.impl.*.*(..)))"></aop:pointcut> <!--配置切面 --> <aop:aspect id="loggerAdvice" ref="loggerUtil"> <!--前置--> <aop:before method="methodBeforeAdvice" pointcut-ref="pointcut"></aop:before> <!--后置--> <aop:after-returning method="afterReturningAdvice" pointcut-ref="pointcut"></aop:after-returning> <!--异常--> <aop:after-throwing method="throwsAdvice" pointcut-ref="pointcut"></aop:after-throwing> <!--最终--> <aop:after method="afterAdvice" pointcut-ref="pointcut"></aop:after> <!--环绕通知--> <aop:around method="aroundAdvice" pointcut-ref="pointcut"></aop:around> </aop:aspect> </aop:config>
其他通知可以通过配置的方式指定增强的代码的执行时机,而环绕通知则可以编码的方式指定。
三、基于注解的AOP配置
@Aspect:指定当前类为切面类 @Pointcut:配置切入点表达式 @Before("切入点方法名"):前置通知 @AfterReturning("切入点方法名"):后置通知 @AfterThrowing("切入点方法名"):异常通知 @After("切入点方法名"):最终通知 @Around("切入点方法名"):环绕通知
配置文件中需要做两件事: 1.配置spring组件扫描包 2.配置开启注解AOP的支持
beans.xml:
xml
复制代码
<?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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 告知 spring 创建容器时要扫描的包 --> <context:component-scan base-package="com.hcx"></context:component-scan> <!-- 配置spring开启注解AOP的支持 --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
LoggerUtil:
java
复制代码
package com.hcx.utils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; /** * Created by hongcaixia on 2019/12/17. */ @Component("loggerUtil") @Aspect//表示当前类是一个切面类 public class LoggerUtil { @Pointcut("execution(* com.hcx.service.impl.*.*(..))") public void pointcut(){ } /** * 前置 */ @Before("pointcut()") public void methodBeforeAdvice(){ System.out.println("前置通知"); } /** * 后置 */ @AfterReturning("pointcut()") public void afterReturningAdvice(){ System.out.println("后置通知"); } /** * 异常 */ @AfterThrowing("pointcut()") public void throwsAdvice(){ System.out.println("异常通知"); } /** * 最终 */ @After("pointcut()") public void afterAdvice(){ System.out.println("最终通知"); } /** * 环绕 */ // @Around("pointcut()") public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){ try { Object[] args = proceedingJoinPoint.getArgs(); //前置通知:proceed方法之前 System.out.println("环绕通知"); //调用切入点方法 Object proceed = proceedingJoinPoint.proceed(args); //后置通知:proceed方法之后 System.out.println("环绕通知"); return proceed; } catch (Throwable throwable) { //异常通知 System.out.println("环绕通知"); throwable.printStackTrace(); }finally{ System.out.println("环绕通知"); } return null; } /** * 引介 */ public void introductionInterceptor(){ System.out.println("引介通知"); } }
打印结果:
复制代码
有异常时: 前置通知 保存账户 最终通知 异常通知 没有异常时: 前置通知 保存账户 最终通知 后置通知
此时顺序有问题,可以使用环绕通知:
java
复制代码
/** * 环绕 */ @Around("pointcut()") public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){ try { Object[] args = proceedingJoinPoint.getArgs(); //前置通知:proceed方法之前 System.out.println("前置通知"); //调用切入点方法 Object proceed = proceedingJoinPoint.proceed(args); //后置通知:proceed方法之后 System.out.println("后置通知"); return proceed; } catch (Throwable throwable) { //异常通知 System.out.println("异常通知"); throwable.printStackTrace(); }finally{ System.out.println("最终通知"); } return null; }
打印顺序:
复制代码
前置通知 保存账户 后置通知 最终通知
使用纯注解的话(没有beans.xml),只需在配置类中添加@EnableAspectJAutoProxy
四、使用SpringAOP记录日志
需求:记录用户操作系统的每个步骤的详细信息
编写切面类:LogAop
java
复制代码
package com.hcx.controller; import com.hcx.domain.SysLog; import com.hcx.service.SysLogService; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Date; /** * Created by hongcaixia on 2020/1/29. */ @Component @Aspect public class LogAop { @Autowired private SysLogService sysLogService; //需要配置一个listener @Autowired private HttpServletRequest request; //开始时间 private Date visitTime; //访问的类 private Class clazz; //访问的方法 private Method method; /** * 前置通知:获取开始时间,执行的类和方法 * * @param joinPoint */ @Before("execution(* com.hcx.controller.*.*(..))") public void doBefore(JoinPoint joinPoint) throws Exception { visitTime = new Date(); clazz = joinPoint.getTarget().getClass(); String methodName = joinPoint.getSignature().getName(); //获取访问的方法的参数 Object[] args = joinPoint.getArgs(); if (args == null || args.length == 0) { //获取无参数的方法 method = clazz.getMethod(methodName); } else { Class[] classArgs = new Class[args.length]; for (int i = 0; i < args.length; i++) { classArgs[i] = args[i].getClass(); } method = clazz.getMethod(methodName, classArgs); } } /** * 后置通知 * * @param joinPoint */ @After("execution(* com.hcx.controller.*.*(..))") public void doAfter(JoinPoint joinPoint) { //访问时长 long time = new Date().getTime() - visitTime.getTime(); String url = ""; //URL if (clazz != null && method != null && clazz != LogAop.class) { //获取类上的注解:@RequestMapping("") RequestMapping clazzAnnotation = (RequestMapping) clazz.getAnnotation(RequestMapping.class); if (clazzAnnotation != null) { String[] clazzValue = clazzAnnotation.value(); //获取方法上的@RequestMapping("") RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class); if (methodAnnotation != null) { String[] methodValue = methodAnnotation.value(); url = clazzValue[0] + methodValue[0]; //获取访问的ip String remoteAddr = request.getRemoteAddr(); //从上下文中获取当前登录的用户 SecurityContext context = SecurityContextHolder.getContext(); User user = (User) context.getAuthentication().getPrincipal(); String username = user.getUsername(); //将日志信息封装到SysLog对象 SysLog sysLog = new SysLog(); sysLog.setVisitTime(visitTime); sysLog.setUsername(username); sysLog.setIp(remoteAddr); sysLog.setUrl(url); sysLog.setExecutionTime(time); sysLog.setMethod("类名:" + clazz.getName() + " 方法名:" + method.getName()); //调用service完成保存操作 sysLogService.save(sysLog); } } } } }
本文介绍了Spring框架中的AOP(面向切面编程)概念,包括连接点、切入点、通知等核心概念,并通过XML配置和注解方式展示了如何进行AOP配置,以实现如事务管理、日志记录等功能。文章还提供了具体的代码示例,展示了在方法执行前后插入增强逻辑的过程。
6531

被折叠的 条评论
为什么被折叠?



