springAOP实现原理
spring AOP实现原理,
spring 会在初始化的时候,创建一个BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator)用来为类注入切面。
AnnotationAwareAspectJAutoProxyCreator 是怎么加载到spring中的?
1. @EnableAutoConfiguration

2. AOPautoConfiguration
@Configuration
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class,
AnnotatedElement.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration { @Configuration
@EnableAspectJAutoProxy(proxyTargetClass = false)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = false)
public static class JdkDynamicAutoProxyConfiguration { } @Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = true)
public static class CglibAutoProxyConfiguration { } }
3. 注入的过程
@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null);
} @Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry,
@Nullable Object source) { return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
}
这个类的作用:
1.拦截 advisor 类。(建议类,为bean加载切面:包括自定的advisor,和transactionAdvisor)
AbstractAutoProxyCreator.java
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
Object cacheKey = getCacheKey(beanClass, beanName);
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
2.拦截带有切面注解的类,和切面定义拦截的类。
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// Create proxy if we have advice.
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
3.创建代理类
3.1根据proxyFactory 获取对应的代理类
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
3.2 使用proxy类,创建 proxyObject (和cglib的用法基本一样。)
enhancer.setSuperclass(proxySuperClass);
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader)); Callback[] callbacks = getCallbacks(rootClass);
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
// fixedInterceptorMap only populated at this point, after getCallbacks call above
enhancer.setCallbackFilter(new ProxyCallbackFilter(
this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types); // Generate the proxy class and create a proxy instance.
return createProxyClassAndInstance(enhancer, callbacks);
4.targetSource 的作用和原理
targetSource 是一个 被代理的对象,用来封装具体的代理对象。所有生成后的代理对象,1.调用切面,2调用targetSource.getTarget(),3.会调用method.Invoke(target,args)
用处:
1.热交换 JndiObjectTargetSource 加载spring时,tomcat先加载了dataSource,此时对已有的dataSource加切面是不和实际的。所以可以对JNDIdatasource加切面,在调用具体的方法时,由targetSource交换的通过jndi查找到的数据源。
为了兼容targetSource有了
SingletonTargetSource,EmptyTargetSource,
springAOP实现原理的更多相关文章
- OOP的完美点缀—AOP之SpringAOP实现原理
OOP的完美点缀-AOP之SpringAOP实现原理 前言 OOP与AOP OOP(Object Oriented Programming,面向对象编程),通过封装.继承将程序抽象为各个层次的对象,进 ...
- SpringAOP实现(原理)
AOP原理: AOP分为:JDK动态代理和CGLIB代理 静态代理:由程序员创建或特定工具自动生成源代码,再对其编译.在程序运行前,代理类的.class文件就已经存在了. 注 ...
- spring框架学习笔记4:SpringAOP实现原理
AOP AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善.OOP引入 ...
- SpringAOP 设计原理
1. 设计原理 引入了,代理模式. java 程序执行流: 如果从虚拟机的角度看,整个程序的过程就是方法的调用,我们按照方法的执行顺序,将方法调用成一串. 在方法之间有着Join Point 连接点 ...
- SpringAop实现原理及代理模式
Spring Aop的原理 Spring的AOP就是通过动态代理实现的.当为某个Bean或者某些Bean配置切面时,Spring会为其创建代理对象,当调用该对象的某个方法时,实际是调用生成的代理类的对 ...
- springAOP配置原理
什么是AOP AOP(Aspect-OrientedProgramming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入 ...
- SpringAOP 原理解析
什么是AOP? 1: 传统的OOP编程他的代码逻辑是一种自上向下, 而在这些自上而下的过程中会产生一些横切性的问题,比如说:日志信息,权限校验认证,事务等, 2: 这些横切性问题,往往与我们的主业务逻 ...
- Spring知识点总结(四)之SpringAOP基础
1. Spring aop中的基本概念 • 连接点(Joinpoint):在程序执行过程中某个特定的点,比如某方法调用的时候或者处理异常的时候.在Spring AOP中,一个连接 ...
- 75道阿里Java面试题,你能答上几道?
整理了下阿里近几年的java面试题目,大家参考下吧,希望对大家有帮助,可以帮大家查漏补缺. 答对以下这些面试题,可以淘汰掉 80 % 的求职竞争者. 1.hashcode相等两个类一定相等吗?equa ...
随机推荐
- OpenCV的视频输入和相似度测量
#include <iostream> #include <string> #include <iomanip> // 控制浮动类型的打印精度 #include & ...
- 快速排序 QuickSort (C++迭代,递归)
/* * QuickSort.h * 快速排序(将每一个元素转换为轴点元素) * Created on: 2020年2月12日 * Author: LuYonglei */ #ifndef SRC_Q ...
- L1-2 倒数第N个字符串
思路 这题就是一道进制转换,用26进制表示一个数,以及26进制下的数的加减操作. 代码 #include <bits/stdc++.h> using namespace std; int ...
- AcWing 差分一维加二维
一维 #include<bits/stdc++.h> using namespace std ; ; int n,m; int a[N],b[N]; //a为前缀和,b为差分 差分和前缀和 ...
- AcWing 794. 高精度除法
https://www.acwing.com/problem/content/796/ #include<bits/stdc++.h> using namespace std; // A/ ...
- MySQL学习(十一)double write 介绍 (半原创)
复习 Innodb关键的特性 插入缓存 两次写 异步IO 刷新邻近页 自适应哈希索引 概述 double write 的主要的作用是保证写入数据库文件的可靠性.通俗地说就是一份数据写两个地方,当出现异 ...
- OO完结篇-第四单元小结
OO第四单元小结 一.作业架构分析. 1.第一次作业 本次作业需要完成UML类图查询. 难点在于初次接触UML,需要对UML进行一定程度的学习和理解. 思路主要是根据每个传进来的element获取其t ...
- 【 SSH 实例】使用ssh开发的简单项目
简单的员工管理项目,使用spring.struts1.hibernate开发 applicationContext.xml <?xml version="1.0" encod ...
- flask 2 进阶
# 创建项目 jinja2 语法基础 # pycharm 里面 创建 new project -->pure python 之后选择路径 选择解释器 以及虚拟环境问题 from flask im ...
- 【深入HTTP协议】
目录 HTTP 请求 HTTP 响应 "HTTP是(Hyper Text Transfer Protocol)超文本传输协议的缩写. HTTP的发展是万维网协会(World Wide Web ...