AOP:简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。
AOP的作用及优势
作用:在程序运行期间,不修改源码对已有方法进行增强。
优势:减少重复代码 提高开发效率 维护方便
关于代理的选择
在spring中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
AOP相关术语
Joinpoint(连接点):即业务层的接口
Pointcut(切入点):即对业务接口进行增强的接口。(连接点不一定是切入点,切入点一定是连接点)
Advice(通知/增强):即增强的类
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
示例代码
/**
* 用于创建客户业务层对象工厂(当然也可以创建其他业务层对象,只不过我们此处不做那么繁琐)
*/
public class BeanFactory {
/**
* 获取客户业务层对象的代理对象
* @return
*/
public static ICustomerService getCustomerService() {
//定义客户业务层对象
final ICustomerService customerService = new CustomerServiceImpl();
//生成它的代理对象
ICustomerService proxyCustomerService = (ICustomerService)
Proxy.newProxyInstance(customerService.getClass().getClassLoader()
,customerService.getClass().getInterfaces(),
new InvocationHandler() {
//执行客户业务层任何方法,都会在此处被拦截,我们对那些方法增强,加入事务。
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
Object rtValue = null;
try{
//开启事务
HibernateUtil.beginTransaction();
//执行操作
rtValue = method.invoke(customerService, args);
//提交事务
HibernateUtil.commit();
}catch(Exception e){
//回滚事务
HibernateUtil.rollback();
e.printStackTrace();
}finally{
//释放资源.hibernate在我们事务操作(提交/回滚)之后,已经帮我们关了。
//如果他没关,我们在此处关
}
return rtValue;
}
});
return proxyCustomerService;
}
}
切入点
前置通知
后置通知
异常通知
最终通知
环绕通知
Target(目标对象):
Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。
Proxy(代理):
Spring基于xml的AOP配置
第一步:把通知类交给spring来管理
<bean id="logger" class="com.itheima.utils.Logger"></bean>
第二步:导入aop名称空间,并且使用aop:config开始aop的配置
<aop:config>
</aop:config>
第三步:使用aop:aspect配置切面 id属性用于给切面提供一个唯一标识。ref属性:用于应用通知Bean的id
<aop:aspect id="logAdvice" ref="logger">
</aop:aspect>
第四步:配置通知的类型,指定增强的方法何时执行。method属性:用于指定增强的方法名称 pointcut属性:用于指定切入点表达式。
<!-- 定义通用的切入点表达式,如果写在aop:aspct标签外部,则表示所有切面可用 -->
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
<aop:before method="printLog" pointcut-ref="pt1"/>
配置切面
<aop:aspect id="logAdvice" ref="logger">
<!-- 配置前置通知: 永远在切入点方法执行之前执行
<aop:before method="beforePrintLog" pointcut-ref="pt1"/>-->
<!-- 配置后置通知: 切入点方法正常执行之后执行
<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"/>-->
<!-- 配置异常通知: 切入点方法执行产生异常之后执行。它和后置通知永远只能执行一个
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"/>-->
<!-- 配置最终通知:无论切入点方法是否正常执行,它都会在其后面执行
<aop:after method="afterPrintLog" pointcut-ref="pt1"/> -->
<!-- 配置环绕通知 -->
<aop:around method="aroundPrintLog" pointcut-ref="pt1"/>
</aop:aspect>
环绕通知(环绕通知是spring提供可以手动控制什么时候执行增强的方式)
/**
* 环绕通知
* 问题:
* 当我们配置了环绕通知之后,切入点方法没有执行,而环绕通知里的代码执行了。
* 分析:
* 由动态代理可知,环绕通知指的是invoke方法,并且里面有明确的切入点方法调用。而我们现在的环绕通知没有明确切入点方法调用。
* 解决:
* spring为我们提供了一个接口:ProceedingJoinPoint。该接口可以作为环绕通知的方法参数来使用。
* 在程序运行时,spring框架会为我们提供该接口的实现类,供我们使用。
* 该接口中有一个方法,proceed(),它的作用就等同于method.invoke方法,就是明确调用业务层核心方法(切入点方法)
*
* 环绕通知:
* 它是spring框架为我们提供的一种可以在代码中手动控制通知方法什么时候执行的方式。
*/
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try {
System.out.println("Logger中的aroundPrintLog方法开始记录日志了。。。。前置");
rtValue = pjp.proceed();
System.out.println("Logger中的aroundPrintLog方法开始记录日志了。。。。后置");
} catch (Throwable e) {
System.out.println("Logger中的aroundPrintLog方法开始记录日志了。。。。异常");
e.printStackTrace();
}finally{
System.out.println("Logger中的aroundPrintLog方法开始记录日志了。。。。最终");
}
return rtValue;
}
spring注解配置AOP
spring配置文件
<?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.itheima"></context:component-scan>
<!-- 开启spring对注解AOP的支持-->
<aop:aspectj-autoproxy />
</beans>
业务层
package com.itheima.service.impl;
import org.springframework.stereotype.Service;
import com.itheima.service.ICustomerService;
/**
* 模拟客户业务层的实现类
* @author zhy
*
*/
@Service("customerService")
public class CustomerServiceImpl implements ICustomerService {
@Override
public void saveCustomer() {
System.out.println("保存了客户");
//int i=1/0;
}
@Override
public void updateCustomer(int i) {
System.out.println("更新了客户。。。"+i);
}
@Override
public int deleteCustomer() {
System.out.println("删除了客户");
return 0;
}
}
通知类
package com.itheima.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* 一个用于记录日志的类
* @author zhy
*
*/
@Component("logger")
@Aspect//配置了切面
public class Logger {
@Pointcut("execution(* com.itheima.service.impl.*.*(..))")
private void pt1(){}
/**
* 前置通知
*/
//@Before("pt1()")
public void beforePrintLog(){
System.out.println("前置:Logger中的beforePrintLog方法开始记录日志了。。。。");
}
/**
* 后置通知
*/
//@AfterReturning("pt1()")
public void afterReturningPrintLog(){
System.out.println("后置:Logger中的afterReturningPrintLog方法开始记录日志了。。。。");
}
/**
* 异常通知
*/
//@AfterThrowing("pt1()")
public void afterThrowingPrintLog(){
System.out.println("异常:Logger中的afterThrowingPrintLog方法开始记录日志了。。。。");
}
/**
* 最终通知
*/
//@After("pt1()")
public void afterPrintLog(){
System.out.println("最终:Logger中的afterPrintLog方法开始记录日志了。。。。");
}
/**
* 环绕通知
* 问题:
* 当我们配置了环绕通知之后,切入点方法没有执行,而环绕通知里的代码执行了。
* 分析:
* 由动态代理可知,环绕通知指的是invoke方法,并且里面有明确的切入点方法调用。而我们现在的环绕通知没有明确切入点方法调用。
* 解决:
* spring为我们提供了一个接口:ProceedingJoinPoint。该接口可以作为环绕通知的方法参数来使用。
* 在程序运行时,spring框架会为我们提供该接口的实现类,供我们使用。
* 该接口中有一个方法,proceed(),它的作用就等同于method.invoke方法,就是明确调用业务层核心方法(切入点方法)
*
* 环绕通知:
* 它是spring框架为我们提供的一种可以在代码中手动控制通知方法什么时候执行的方式。
*/
@Around("pt1()")
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try {
System.out.println("Logger中的aroundPrintLog方法开始记录日志了。。。。前置");
rtValue = pjp.proceed();
System.out.println("Logger中的aroundPrintLog方法开始记录日志了。。。。后置");
} catch (Throwable e) {
System.out.println("Logger中的aroundPrintLog方法开始记录日志了。。。。异常");
e.printStackTrace();
}finally{
System.out.println("Logger中的aroundPrintLog方法开始记录日志了。。。。最终");
}
return rtValue;
}
}