什么是AOP
- AOP(Aspect-Oriented Programming 面向切面编程),是OOP(Object-Oriented Programming)面向对象编程的补充和完善,OOP引入封装。继承,多态等概念建立的一种对象层次结构,用以模拟公共行为的集合。当需要为分散的对象引入公共行为时,OOP无能为力,OOP允许定义从上到下的关系,但是不适合从左到右的关系,例如日志功能,日志功能旺旺水平散布在所有对象层次中,而和他所散布的对象的核心功能毫无关系,对于其他类型的代码,如安全性,异常处理和透明的持续性也是如此。这种散布在各处的无关代码被称之为横切(cross-cutting)代码,在OOP中国它导致大量代码重复,不利于各模块的重用。
而AOP技术则相反,它利用“横切”的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为“Aspect”切面,切面就是将那些与业务无关,却为业务模块所共同调用的逻辑或者责任封装起来,便于减少系统的重复代码,降低模块的耦合度,并有利于未来的可操作性和可维护性。
AOP代表的是横向关系,如果说对象是一个空心圆柱体,其中封装的是对象的属性和行为,AOP编程就是一把刀,将空心圆柱体破开,以获取其内部的消息,而剖开的切面就是“切面”,然后又将其复原不留痕迹。
使用“横切”技术,AOP把软件系统分为两部分**“核心关注点”和“横切关注点”** ,业务处理的主要流程是核心关注点,与之关系不大的部分是横切关注点。横切关注点的一个特点是:他们经常发生在核心关注点的多处,而各处都基本相似。比如权限认证,日志,事务处理。 AOP的作用在于分离系统中的各种关注点。将核心关注点和横切关注点分离出来。“将应用程序中的商业逻辑同对其提供支持的通用服务进行分离”--------Magee.
实现AOP的技术:
-
- 采用动态代理
利用拦截方法的方式,对该方法进行装饰,以取代原有对象行为的执行;
- 采用动态代理
-
- 采用静态织入的方式,引入特定的语法创建“切面”,从而使得编译器可以在编译期间织入有关“切面”的代码。
AOP术语:
- 切面(Aspect)
— 横切关注点的模块化(跨越应用程序多个模块的功能,比如 日志功能),这个关注点实现可能另外横切多个对象。 - 通知(Advice)
— 在AOP中。描述切面要完成的工作被称之为:通知
AOP可以应用的5种类型的通知: - 前置通知(Before):
—在目标方法被调用之前调用通知功能 - 后置通知(After):
—在目标方法完成之后调用通知,此时不会关心方法的输出是什么。 - 返回通知(After-returning):
— 目标方法成功执行之后调用通知。 - 异常通知(After-throwing):
— 在目标方法抛出异常后调用通知。 - 环绕通知(Around)
—:通知包裹了呗=被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为。 - 目标(Target):
— 包含连接点的对象,也被称做被通知或代理对象。 - 代理(Proxy)
— 向目标对象应用通知之后创建的对象,在Spring中,AOP代理可以是JDK动态代理或者CGLIB代理。 - 连接点(Join point)
— 连接点是在应用执行过程中能够插入切面的一个点。这个点可以是类 的某个方法调用前,调用后,方法抛出异常后等。切面代码可以利用这些点插入到应用的正常流程之中,并添加行为。 - 切点(Pointcut)
— 指定一个通知将被引发的一系列连接点的集合,AOP通过切点定位到特定的连接点。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过org.springframework.aop.Pointcut 接口进行描述,他使用类和方法作为连接点的查询条件。每个类都拥有多个连接点,如:ArithmethicCalculator类的所有的方法实际上都是连接点。 - 引入(Introduction)
— 引入允许我们向现有的类添加新的放啊发和属性(Spring 提供一个方法注入的功能) - 织入(Weaving)
— 织入描述的是把切面应用到目标对象来创建新的代理对象的过程。
手动推进目标方法运行(joinPoint.procced())
Spring AOP 的切面在运行时被织入,原理是使用了动态代理技术。Spring支持两种方式生成代理对象:JDK动态代理和CGLIB,默认的策略是如果目标类是接口,则使用JDK 动态代理技术,否则使用CGLIB来生成代理。
Spring AOP使用
在spring2.0 以上的版本中,可以使用基于Aspect 注解或基于XML配置的AOP
@Aspect 表示该类为切面类:
可以在通知方法中声明声明一个类型为JoinPoint 的参数。这样我们就可以访问到连接名的细节信息,如方法名称,参数值等
- 如:@Around(“execution(String com.feifan.service.impl.UserServiceImpl.login(String, String))”)表达式为例:
—AspectJ 切入点表达式:
—execution:表示在方法执行时触发
—修饰符及返回值类型:表示方法修饰符及返回值类型,* 代表任意修饰符及任意返回值类型。
—方法名:包括方法所属的类名与方法名
—参数:表示方法形参,(…)匹配任意数量的参数
@Pointcut:切入点表达式
/**
* 定义一个方法,用于声明切入点表达式,一般地,该方法中不需要添加其他的代码
* 使用@PointCut 来声明切入点表达式
* 后面的其他通知直接使用方法名引用当前的切入点表达式
*/
@Pointcut("execution(* com.feifan.service.UserService.*(..))")
public void pointcut() {}
/**
* 环绕通知要携带 ProceedingJoinPoint 类型的参数。
* 环绕通知类似动态代理,ProceedingJoinPoint 类型的参数,可以决定是否执行目标方法
* 且环绕通知必须有返回值,返回值即为目标方法的返回值
* @param ProceedingJoinPoint
* @param result
* @return
*/
//@Around(value="execution(int com.feifan.service.UserServiceImpl.div(int, int))") 指定单一的方法
//
//@Around("execution(* com.feifan.service.UserService.*(..))") // UserService 切UserService 接口里面的所有的方法
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) {
Object result=null;
try {
System.out.println("Around 方法执行之前:");
result = joinPoint.proceed();
System.out.println("Around 方法正常结束后:");
} catch (Throwable e) {
e.printStackTrace();
System.out.println("Around 方法 执行异常");
}
System.out.println("after Around 方法执行之后");
return result;
}
@Order(2) 数字越小优先级越高
例子—基于注解开发:
-
- SpringConfig.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 启用AspectJ 自动代理 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- 自动包扫描 -->
<context:component-scan base-package="com.feifan"></context:component-scan>
</beans>
- 1.1 POM.xml依赖:
<dependencies>
<!-- 添加AOP依赖 (整合aspect框架完成AOP功能) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
</dependencies>
-
- 声明接口:UserService.java
public interface UserService {
public String login(String username,String password);
public String register(String username,String password);
int div(int i,int j);
}
-
- 声明接口的实现类:
package com.feifan.service;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.feifan.service.UserService;
@Component
public class UserServiceImpl implements UserService {
@Override
public String login(String username, String password) {
System.out.println("username+"+username+"password+"+password);
return "login OK";
}
@Override
public String register(String username, String password) {
System.out.println("username+"+username+"password+"+password);
return "register OK";
}
@Override
public int div(int i, int j) {
return i/j;
}
}
-
- 声明切面类AOP.Java
package com.feifan.aop;
import org.aspectj.lang.JoinPoint;
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;
@Aspect
@Component
public class AOP {
/**
* 定义一个方法,用于声明切入点表达式,一般地,该方法中不需要添加其他的代码
* 使用@PointCut 来声明切入点表达式
* 后面的其他通知直接使用方法名引用当前的切入点表达式
*/
@Pointcut("execution(* com.feifan.service.UserService.*(..))")
public void pointcut() {}
@Before("execution(int com.feifan.service.MulCalcutor.add(int, int))")
public void before( JoinPoint joinPoint) {
System.out.println("AOP before");
System.out.println(joinPoint.getTarget());
System.out.println(joinPoint.getArgs());
System.out.println(joinPoint.getSignature().getName());
System.out.println(joinPoint.getSourceLocation());
}
@Before("execution(String com.feifan.service.UserService.login(String, String))")
public void loginBefore(JoinPoint joinPoint) {
System.out.println("login before:"+joinPoint.getSignature().getName());
System.out.println(joinPoint.getArgs().toString());
}
/**
* 目标方法执行之后(不管是否异常,后置通知娶不到执行的结果)
* @param joinPoint
*/
//@After("execution(public String com.feifan.service.impl.UserServiceImpl.login(String,String))")
@After("execution(String com.feifan.service.UserService.login(String, String))")
public void afterExector(JoinPoint joinPoint) {
String methodName=joinPoint.getSignature().getName();
System.out.println("后置通知:method执行OK"+methodName);
}
/**
* 方法执行完正常
* @param joinPoint
* @param result 获取方法的返回值
*/
@AfterReturning(value="execution(String com.feifan.service.UserService.login(String, String))",returning="result")
public void afterReturning(JoinPoint joinPoint,Object result) {
System.out.println(joinPoint.getSignature().getName());
System.out.println(result);
}
/**
* 可以指定特定异常Exception e ===>>> nullPointException
* @param joinPoint
* @param e 异常
*/
@AfterThrowing(value="execution(int com.feifan.service.UserServiceImpl.div(int, int))",throwing="e")
public void afterException(JoinPoint joinPoint,Exception e) {
System.out.println(e);
}
/**
* 环绕通知要携带 ProceedingJoinPoint 类型的参数。
* 环绕通知类似动态代理,ProceedingJoinPoint 类型的参数,可以决定是否执行目标方法
* 且环绕通知必须有返回值,返回值即为目标方法的返回值
* @param ProceedingJoinPoint
* @param result
* @return
*/
//@Around(value="execution(int com.feifan.service.UserServiceImpl.div(int, int))") 指定单一的方法
//
//@Around("execution(* com.feifan.service.UserService.*(..))") // UserService 切UserService 接口里面的所有的方法
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) {
//截取请求信息
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
Object result=null;
try {
System.out.println("Around 方法执行之前:");
result = joinPoint.proceed();
System.out.println("Around 方法正常结束后:");
} catch (Throwable e) {
e.printStackTrace();
System.out.println("Around 方法 执行异常");
}
System.out.println("after Around 方法执行之后");
return result;
}
}
-
- 测试1:
package aop;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.feifan.service.MulCalcutor;
import com.feifan.service.UserService;
public class test {
public static void main(String[] args) {
//1. 创建IOC容器
ClassPathXmlApplicationContext cac = new ClassPathXmlApplicationContext("SpringConfig.xml");
//2.从IOC容器中获取Bean
MulCalcutor mulCalcutor = (MulCalcutor) cac.getBean(MulCalcutor.class);
mulCalcutor.add(3, 5);
UserService userService=(UserService)cac.getBean(UserService.class);
//3.执行对应的方法
userService.login("kk", "ss");
userService.div(2, 0);
cac.close();
}
}
结果:
-
- 测试2:
注解配置类的形式
- 测试2:
package com.feifan.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration//声明是一个配置文件
@ComponentScan(basePackages="com.feifan")
public class SpringConfig {
}
- 测试类
package aop;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.feifan.config.SpringConfig;
import com.feifan.service.MulCalcutor;
import com.feifan.service.UserService;
public class test2 {
public static void main(String[] args) {
//1. 创建IOC容器
AnnotationConfigApplicationContext cac=new AnnotationConfigApplicationContext(SpringConfig.class);
//2.从IOC容器中获取Bean
MulCalcutor mulCalcutor = (MulCalcutor) cac.getBean(MulCalcutor.class);
mulCalcutor.add(3, 5);
UserService userService=(UserService)cac.getBean(UserService.class);
//3.执行对应的方法
userService.login("kk", "ss");
userService.div(2, 0);
cac.close();
}
}
-
- 基于xml配置 AOP
SpringConfig.xml
- 基于xml配置 AOP
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 配置Bean -->
<bean id="userServiceImpl" class="com.feifan.xml.UserServiceImpl"/>
<bean id="mulCalcutorImpl" class="com.feifan.xml.MulCalcutorImpl"/>
<!-- 配置切面Bean -->
<bean id="aop" class="com.feifan.xml.AOP"/>
<!-- 配置AOP切面 -->
<aop:config>
<!-- 配置切入点表达式 -->
<!-- UserService 接口里面的所有方法 -->
<aop:pointcut expression="execution(* com.feifan.xml.UserService.*(..))" id="pointcut"/>
<!--配置切面及通知 -->
<aop:aspect ref="aop" order="1">
<aop:before method="loginBefore" pointcut-ref="pointcut"/>
<aop:after method="afterExector" pointcut-ref="pointcut"/>
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
<aop:after-throwing method="afterException" pointcut-ref="pointcut" throwing="e"/>
<aop:around method="around" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>
AOP切面类
package com.feifan.xml;
import org.aspectj.lang.JoinPoint;
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;
public class AOP {
/**
* 定义一个方法,用于声明切入点表达式,一般地,该方法中不需要添加其他的代码
* 使用@PointCut 来声明切入点表达式
* 后面的其他通知直接使用方法名引用当前的切入点表达式
*/
//@Pointcut("execution(* com.feifan.service.UserService.*(..))")
public void pointcut() {}
//@Before("execution(int com.feifan.service.MulCalcutor.add(int, int))")
public void before( JoinPoint joinPoint) {
System.out.println("AOP before");
System.out.println(joinPoint.getTarget());
System.out.println(joinPoint.getArgs());
System.out.println(joinPoint.getSignature().getName());
System.out.println(joinPoint.getSourceLocation());
}
//@Before("execution(String com.feifan.service.UserService.login(String, String))")
public void loginBefore(JoinPoint joinPoint) {
System.out.println("login before:"+joinPoint.getSignature().getName());
System.out.println(joinPoint.getArgs().toString());
}
/**
* 目标方法执行之后(不管是否异常,后置通知娶不到执行的结果)
* @param joinPoint
*/
//@After("execution(public String com.feifan.service.impl.UserServiceImpl.login(String,String))")
//@After("execution(String com.feifan.service.UserService.login(String, String))")
public void afterExector(JoinPoint joinPoint) {
String methodName=joinPoint.getSignature().getName();
System.out.println("后置通知:method执行OK"+methodName);
}
/**
* 方法执行完正常
* @param joinPoint
* @param result 获取方法的返回值
*/
//@AfterReturning(value="execution(String com.feifan.service.UserService.login(String, String))",returning="result")
public void afterReturning(JoinPoint joinPoint,Object result) {
System.out.println(joinPoint.getSignature().getName());
System.out.println(result);
}
/**
* 可以指定特定异常Exception e ===>>> nullPointException
* @param joinPoint
* @param e 异常
*/
//@AfterThrowing(value="execution(int com.feifan.service.UserServiceImpl.div(int, int))",throwing="e")
public void afterException(JoinPoint joinPoint,Exception e) {
System.out.println(e);
}
/**
* 环绕通知要携带 ProceedingJoinPoint 类型的参数。
* 环绕通知类似动态代理,ProceedingJoinPoint 类型的参数,可以决定是否执行目标方法
* 且环绕通知必须有返回值,返回值即为目标方法的返回值
* @param ProceedingJoinPoint
* @param result
* @return
*/
//@Around(value="execution(int com.feifan.service.UserServiceImpl.div(int, int))") 指定单一的方法
//
//@Around("execution(* com.feifan.service.UserService.*(..))") // UserService 切UserService 接口里面的所有的方法
//@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) {
Object result=null;
try {
System.out.println("Around 方法执行之前:");
result = joinPoint.proceed();
System.out.println("Around 方法正常结束后:");
} catch (Throwable e) {
e.printStackTrace();
System.out.println("Around 方法 执行异常");
}
System.out.println("after Around 方法执行之后");
return result;
}
}
UserService接口
package com.feifan.xml;
public interface UserService {
public String login(String username,String password);
public String register(String username,String password);
int div(int i,int j);
}
UserServiceImpl实现类
package com.feifan.xml;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Component
public class UserServiceImpl implements UserService {
@Override
public String login(String username, String password) {
System.out.println("username+"+username+"password+"+password);
return "login OK";
}
@Override
public String register(String username, String password) {
System.out.println("username+"+username+"password+"+password);
return "register OK";
}
@Override
public int div(int i, int j) {
return i/j;
}
}
MulCalcutor.java
package com.feifan.xml;
public interface MulCalcutor {
int add(int i,int j);
int sub(int i,int j);
int div(int i,int j);
}
实现类
package com.feifan.xml;
import org.springframework.stereotype.Component;
@Component
public class MulCalcutorImpl implements MulCalcutor {
@Override
public int add(int i, int j) {
System.out.println(i+j);
return i+j;
}
@Override
public int sub(int i, int j) {
return i-j;
}
@Override
public int div(int i, int j) {
return i/j;
}
}
测试方法:
package aop;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.feifan.xml.MulCalcutor;
import com.feifan.xml.UserService;
public class test3 {
public static void main(String[] args) {
//1. 创建IOC容器
ClassPathXmlApplicationContext cac = new ClassPathXmlApplicationContext("SpringConfig2.xml");
//2.从IOC容器中获取Bean
MulCalcutor mulCalcutor = (MulCalcutor) cac.getBean(MulCalcutor.class);
mulCalcutor.add(3, 5);
UserService userService=(UserService)cac.getBean(UserService.class);
//3.执行对应的方法
userService.login("kk", "ss");
userService.div(2, 0);
cac.close();
}
}
测试结果:
源码地址:仅供参考
链接:https://pan.baidu.com/s/1BsjIAXYHe8njRSvnmK2F3g
提取码:uyuz
配置文件中启用AspectJ自动代理
总结:
/**
- AOP:【动态代理】
-
指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式;
- 1、导入aop模块;Spring AOP:(spring-aspects)
- 2、定义一个业务逻辑类(MathCalculator);在业务逻辑运行的时候将日志进行打印(方法之前、方法运行结束、方法出现异常,xxx)
- 3、定义一个日志切面类(LogAspects):切面类里面的方法需要动态感知MathCalculator.div运行到哪里然后执行;
-
通知方法:
-
前置通知(@Before):logStart:在目标方法(div)运行之前运行
-
后置通知(@After):logEnd:在目标方法(div)运行结束之后运行(无论方法正常结束还是异常结束)
-
返回通知(@AfterReturning):logReturn:在目标方法(div)正常返回之后运行
-
异常通知(@AfterThrowing):logException:在目标方法(div)出现异常以后运行
-
环绕通知(@Around):动态代理,手动推进目标方法运行(joinPoint.procced())
- 4、给切面类的目标方法标注何时何地运行(通知注解);
- 5、将切面类和业务逻辑类(目标方法所在类)都加入到容器中;
- 6、必须告诉Spring哪个类是切面类(给切面类上加一个注解:@Aspect)
- [7]、给配置类中加 @EnableAspectJAutoProxy 【开启基于注解的aop模式】
-
在Spring中很多的 @EnableXXX;
- 三步:
- 1)、将业务逻辑组件和切面类都加入到容器中;告诉Spring哪个是切面类(@Aspect)
- 2)、在切面类上的每一个通知方法上标注通知注解,告诉Spring何时何地运行(切入点表达式)
- 3)、开启基于注解的aop模式;@EnableAspectJAutoProxy
- AOP原理:【看给容器中注册了什么组件,这个组件什么时候工作,这个组件的功能是什么?】
-
@EnableAspectJAutoProxy;
- 1、@EnableAspectJAutoProxy是什么?
-
@Import(AspectJAutoProxyRegistrar.class):给容器中导入AspectJAutoProxyRegistrar
-
利用AspectJAutoProxyRegistrar自定义给容器中注册bean;BeanDefinetion
-
internalAutoProxyCreator=AnnotationAwareAspectJAutoProxyCreator
-
给容器中注册一个AnnotationAwareAspectJAutoProxyCreator;
- 2、 AnnotationAwareAspectJAutoProxyCreator:
-
AnnotationAwareAspectJAutoProxyCreator
-
->AspectJAwareAdvisorAutoProxyCreator
-
->AbstractAdvisorAutoProxyCreator
-
->AbstractAutoProxyCreator
-
implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware
-
关注后置处理器(在bean初始化完成前后做事情)、自动装配BeanFactory
- AbstractAutoProxyCreator.setBeanFactory()
- AbstractAutoProxyCreator.有后置处理器的逻辑;
- AbstractAdvisorAutoProxyCreator.setBeanFactory()-》initBeanFactory()
- AnnotationAwareAspectJAutoProxyCreator.initBeanFactory()
- 流程:
-
1)、传入配置类,创建ioc容器
-
2)、注册配置类,调用refresh()刷新容器;
-
3)、registerBeanPostProcessors(beanFactory);注册bean的后置处理器来方便拦截bean的创建;
-
1)、先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor
-
2)、给容器中加别的BeanPostProcessor
-
3)、优先注册实现了PriorityOrdered接口的BeanPostProcessor;
-
4)、再给容器中注册实现了Ordered接口的BeanPostProcessor;
-
5)、注册没实现优先级接口的BeanPostProcessor;
-
6)、注册BeanPostProcessor,实际上就是创建BeanPostProcessor对象,保存在容器中;
-
创建internalAutoProxyCreator的BeanPostProcessor【AnnotationAwareAspectJAutoProxyCreator】
-
1)、创建Bean的实例
-
2)、populateBean;给bean的各种属性赋值
-
3)、initializeBean:初始化bean;
-
1)、invokeAwareMethods():处理Aware接口的方法回调
-
2)、applyBeanPostProcessorsBeforeInitialization():应用后置处理器的postProcessBeforeInitialization()
-
3)、invokeInitMethods();执行自定义的初始化方法
-
4)、applyBeanPostProcessorsAfterInitialization();执行后置处理器的postProcessAfterInitialization();
-
4)、BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator)创建成功;--》aspectJAdvisorsBuilder
-
7)、把BeanPostProcessor注册到BeanFactory中;
-
beanFactory.addBeanPostProcessor(postProcessor);
- =以上是创建和注册AnnotationAwareAspectJAutoProxyCreator的过程==
-
AnnotationAwareAspectJAutoProxyCreator => InstantiationAwareBeanPostProcessor
-
4)、finishBeanFactoryInitialization(beanFactory);完成BeanFactory初始化工作;创建剩下的单实例bean
-
1)、遍历获取容器中所有的Bean,依次创建对象getBean(beanName);
-
getBean->doGetBean()->getSingleton()->
-
2)、创建bean
-
【AnnotationAwareAspectJAutoProxyCreator在所有bean创建之前会有一个拦截,InstantiationAwareBeanPostProcessor,会调用postProcessBeforeInstantiation()】
-
1)、先从缓存中获取当前bean,如果能获取到,说明bean是之前被创建过的,直接使用,否则再创建;
-
只要创建好的Bean都会被缓存起来
-
2)、createBean();创建bean;
-
AnnotationAwareAspectJAutoProxyCreator 会在任何bean创建之前先尝试返回bean的实例
-
【BeanPostProcessor是在Bean对象创建完成初始化前后调用的】
-
【InstantiationAwareBeanPostProcessor是在创建Bean实例之前先尝试用后置处理器返回对象的】
-
1)、resolveBeforeInstantiation(beanName, mbdToUse);解析BeforeInstantiation
-
希望后置处理器在此能返回一个代理对象;如果能返回代理对象就使用,如果不能就继续
-
1)、后置处理器先尝试返回对象;
-
bean = applyBeanPostProcessorsBeforeInstantiation():
-
拿到所有后置处理器,如果是InstantiationAwareBeanPostProcessor;
-
就执行postProcessBeforeInstantiation
-
if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); }
-
2)、doCreateBean(beanName, mbdToUse, args);真正的去创建一个bean实例;和3.6流程一样;
-
3)、
- AnnotationAwareAspectJAutoProxyCreator【InstantiationAwareBeanPostProcessor】 的作用:
- 1)、每一个bean创建之前,调用postProcessBeforeInstantiation();
-
关心MathCalculator和LogAspect的创建
-
1)、判断当前bean是否在advisedBeans中(保存了所有需要增强bean)
-
2)、判断当前bean是否是基础类型的Advice、Pointcut、Advisor、AopInfrastructureBean,
-
或者是否是切面(@Aspect)
-
3)、是否需要跳过
-
1)、获取候选的增强器(切面里面的通知方法)【List<Advisor> candidateAdvisors】
-
每一个封装的通知方法的增强器是 InstantiationModelAwarePointcutAdvisor;
-
判断每一个增强器是否是 AspectJPointcutAdvisor 类型的;返回true
-
2)、永远返回false
- 2)、创建对象
- postProcessAfterInitialization;
-
return wrapIfNecessary(bean, beanName, cacheKey);//包装如果需要的情况下
-
1)、获取当前bean的所有增强器(通知方法) Object[] specificInterceptors
-
1、找到候选的所有的增强器(找哪些通知方法是需要切入当前bean方法的)
-
2、获取到能在bean使用的增强器。
-
3、给增强器排序
-
2)、保存当前bean在advisedBeans中;
-
3)、如果当前bean需要增强,创建当前bean的代理对象;
-
1)、获取所有增强器(通知方法)
-
2)、保存到proxyFactory
-
3)、创建代理对象:Spring自动决定
-
JdkDynamicAopProxy(config);jdk动态代理;
-
ObjenesisCglibAopProxy(config);cglib的动态代理;
-
4)、给容器中返回当前组件使用cglib增强了的代理对象;
-
5)、以后容器中获取到的就是这个组件的代理对象,执行目标方法的时候,代理对象就会执行通知方法的流程;
- 3)、目标方法执行 ;
-
容器中保存了组件的代理对象(cglib增强后的对象),这个对象里面保存了详细信息(比如增强器,目标对象,xxx);
-
1)、CglibAopProxy.intercept();拦截目标方法的执行
-
2)、根据ProxyFactory对象获取将要执行的目标方法拦截器链;
-
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
-
1)、List<Object> interceptorList保存所有拦截器 5
-
一个默认的ExposeInvocationInterceptor 和 4个增强器;
-
2)、遍历所有的增强器,将其转为Interceptor;
-
registry.getInterceptors(advisor);
-
3)、将增强器转为List<MethodInterceptor>;
-
如果是MethodInterceptor,直接加入到集合中
-
如果不是,使用AdvisorAdapter将增强器转为MethodInterceptor;
-
转换完成返回MethodInterceptor数组;
-
3)、如果没有拦截器链,直接执行目标方法;
-
拦截器链(每一个通知方法又被包装为方法拦截器,利用MethodInterceptor机制)
-
4)、如果有拦截器链,把需要执行的目标对象,目标方法,
-
拦截器链等信息传入创建一个 CglibMethodInvocation 对象,
-
并调用 Object retVal = mi.proceed();
-
5)、拦截器链的触发过程;
-
1)、如果没有拦截器执行执行目标方法,或者拦截器的索引和拦截器数组-1大小一样(指定到了最后一个拦截器)执行目标方法;
-
2)、链式获取每一个拦截器,拦截器执行invoke方法,每一个拦截器等待下一个拦截器执行完成返回以后再来执行;
-
拦截器链的机制,保证通知方法与目标方法的执行顺序;
- 总结:
-
1)、 @EnableAspectJAutoProxy 开启AOP功能
-
2)、 @EnableAspectJAutoProxy 会给容器中注册一个组件 AnnotationAwareAspectJAutoProxyCreator
-
3)、AnnotationAwareAspectJAutoProxyCreator是一个后置处理器;
-
4)、容器的创建流程:
-
1)、registerBeanPostProcessors()注册后置处理器;创建AnnotationAwareAspectJAutoProxyCreator对象
-
2)、finishBeanFactoryInitialization()初始化剩下的单实例bean
-
1)、创建业务逻辑组件和切面组件
-
2)、AnnotationAwareAspectJAutoProxyCreator拦截组件的创建过程
-
3)、组件创建完之后,判断组件是否需要增强
-
是:切面的通知方法,包装成增强器(Advisor);给业务逻辑组件创建一个代理对象(cglib);
-
5)、执行目标方法:
-
1)、代理对象执行目标方法
-
2)、CglibAopProxy.intercept();
-
1)、得到目标方法的拦截器链(增强器包装成拦截器MethodInterceptor)
-
2)、利用拦截器的链式机制,依次进入每一个拦截器进行执行;
-
3)、效果:
-
正常执行:前置通知-》目标方法-》后置通知-》返回通知
-
出现异常:前置通知-》目标方法-》后置通知-》异常通知
*/
配置类: