1. 目录

[TOC]

2. 说明

AOP动态代理是在bean初始化的过程中,在两个地方执行

  1. doCreateBean()->initializeBean()->applyBeanPostProcessorsAfterInitialization()后处理中执行
  2. 添加Bean到singletonFactories时创建的匿名内部类中。调用的时候是在doGetBean()中的getSingleton方法,执行内部类方法getEarlyBeanReference()

两个地方的处理类均为AnnotationAwareAspectJAutoProxyCreator,将原来的bean通过动态代理解析成代理之后的bean

3. 依赖分析

4. 源码分析

1
2
3
4
5
6
7
8
9
10
11
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
//执行代理包装
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}

4.1. wrapIfNecessary() 执行代理包装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;
}

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;
}

4.1.1. createProxy() 创建代理

此处就是创建一个代理工厂ProxyFactory,加入源对象,在利用工厂生成代理类,具体的逻辑就不分析了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 其余都不用管,只需要关注proxyFactory.setTargetSource(targetSource)和 return处
protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
@Nullable Object[] specificInterceptors, TargetSource targetSource) {

if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
}

ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);

if (!proxyFactory.isProxyTargetClass()) {
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true);
}
else {
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}

Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
proxyFactory.addAdvisors(advisors);
//将代理类加入Factory工厂中
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);

proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
//返回代理对象,已经不涉及到spring容器相关的东西了
//这里面就不在跟踪了,就是根据jdk或cglib创建对应的代理
return proxyFactory.getProxy(getProxyClassLoader());
}

5. 总结

6. 注意事项