一、AOP编程思想
在多数业务场景下,往往会出现下述类型的代码块:他们和业务逻辑并无关系,只是实现一些日志打印、权限管理或事务回滚等操作。而这些逻辑往往会存在在许多个方法中,如果需要调整这些逻辑,那么就需要逐个方法的修改,这些逻辑就称为横切逻辑,下图为横切逻辑的图解:
如图所示,run方法和eat方法均需要打印方法开始执行时间start及方法执行结束时间end,那么打印start的逻辑及打印end的逻辑就称为横切逻辑。
为了解决横切逻辑和业务逻辑的耦合问题,即在保证不影响原有的业务逻辑情况下,将横切逻辑嵌入到其中,这个就是AOP编程需要解决的核心问题。
二、AOP的实现原理
AOP解决的核心问题即在不改变原有业务逻辑的情况下,嵌入横切逻辑,也就是说既要执行原有业务逻辑,同时又对其进行一个增强,需要实现上述需求,那么就要用到Java的动态代理机制,在此简单阐述一下动态代理机制:
动态代理:通过给委托对象创建代理对象,在代理对象中,用户可根据需求对于原有的业务逻辑进行增强,最终由代理对象去实现真正的业务逻辑,如下代码为jdk代理对象的创建方式:
// 获取代理对象
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try{
// 开启事务(关闭事务的自动提交)
transactionManager.beginTransaction();
result = method.invoke(obj,args);
// 提交事务
transactionManager.commit();
}catch (Exception e) {
e.printStackTrace();
// 回滚事务
transactionManager.rollback();
// 抛出异常便于上层servlet捕获
throw e;
}
return result;
}
});
通过传入ClassLoader 类加载器、Class<?>[] 委托对象实现接口的类型及InvocationHandler 拦截器接口 创建代理对象,并通过重写InvocationHandler的invoke方法,实现对于原有代码逻辑的增强,如上代码块所示,在invoke方法中,实现了事务的提交及回滚,并使用method.invoke(obj,args);方法,执行原有的业务逻辑。
那么AOP编程就是为委托对象创建了代理对象,在重写invoke方法时嵌入横切逻辑,并执行原有的业务逻辑,最终由代理对象代替委托对象去执行业务逻辑。
下面为动态代理实现AOP的图解。
三、Spring中的AOP实现
以下是Spring中XML模式实现AOP:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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"
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
">
// 开启注解扫描,base-package指定扫描的包路径
<context:component-scan base-package="com.lagou.edu"/>
// 引入外部资源文件
<context:property-placeholder location="classpath:jdbc.properties"/>
// 第三方jar中的bean定义在xml中
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
// lazy-init:延迟加载,true代表延迟,false代表立即加载,默认是false
<bean id="lazyResult" class="com.lagou.edu.pojo.Result" init-method="initMethod"/>
// 进行aop相关的xml配置,配置aop的过程其实就是把aop相关术语落地
// 横切逻辑bean
<bean id="logUtils" class="com.lagou.edu.utils.LogUtils"></bean>
/* 使用config标签表明开始aop配置,在内部配置切面aspect,
aspect = 切入点(锁定方法) + 方位点(锁定方法中的特殊时机)+ 横切逻辑*/
<aop:config>
<aop:aspect id="logAspect" ref="logUtils">
// 切入点锁定我们感兴趣的方法,使用aspectj语法表达式
<aop:pointcut id="pt1" expression="execution(* *..*.*(..))"/>
<aop:pointcut id="pt1" expression="execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))"/>
// 方位信息,pointcut-ref关联切入点
aop:before前置通知/增强
<aop:before method="beforeMethod" pointcut-ref="pt1"/>
/* aop:after,最终通知,无论如何都执行;aop:after-returnning,正常执行通知*/
<aop:after-returning method="successMethod" returning="retVal" pointcut-ref="pt1"/>
// aop:after-throwing,异常通知
<aop:around method="arroundMethod" pointcut-ref="pt1"/>
</aop:aspect>
</aop:config>
// 开启aop注解驱动proxy-target-class:true强制使用cglib
<aop:aspectj-autoproxy/>
</beans>
同样的,使用纯注解模式也可实现AOP,我们需要在横切逻辑类中通过注解指定切面及切入点即可,如下代码块所示:
@Component
@Aspect
public class LogUtils {
// 指定切面,即针对impl包下所有类的所有方法生效。
@Pointcut("execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))")
public void pt1(){
}
/**
* 业务逻辑开始之前执行
*/
@Before("pt1()")
public void beforeMethod(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
System.out.println(arg);
}
System.out.println("业务逻辑开始执行之前执行.......");
}
/**
* 业务逻辑结束时执行(无论异常与否)
*/
@After("pt1()")
public void afterMethod() {
System.out.println("业务逻辑结束时执行,无论异常与否都执行.......");
}
/**
* 异常时时执行
*/
@AfterThrowing("pt1()")
public void exceptionMethod() {
System.out.println("异常时执行.......");
}
/**
* 业务逻辑正常时执行
*/
@AfterReturning(value = "pt1()",returning = "retVal")
public void successMethod(Object retVal) {
System.out.println("业务逻辑正常时执行.......");
}
/**
* 环绕通知
*
*/
/*@Around("pt1()")*/
public Object arroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕通知中的beforemethod....");
Object result = null;
try{
// 控制原有业务逻辑是否执行
// result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
}catch(Exception e) {
System.out.println("环绕通知中的exceptionmethod....");
}finally {
System.out.println("环绕通知中的after method....");
}
return result;
}
}
