一、AOP动态代理对象创建初探
1 前置知识
https://www.yuque.com/wuxiangwuwo/dfvedv/vd90qo#ttKT4
AbstractAutowireCapableBeanFactory类的doCreateBean方法是创建bean的开始,doCreateBean调用的AbstractAutowireCapableBeanFactory#initializeBean方法负责初始化bean,initializeBean方法调用的AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization方法负责执行BeanPostProcessor的接口实现类中的postProcessAfterInitialization方法。
2 AbstractAutoProxyCreator#postProcessAfterInitialization
创建代理对象的后置处理器AbstractAutoProxyCreator#postProcessAfterInitialization
/*** Create a proxy with the configured interceptors if the bean is* identified as one to proxy by the subclass.* @see #getAdvicesAndAdvisorsForBean*/@Overridepublic Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {if (bean != null) {// 检查下该类是否已经暴露过了// (可能已经创建了,⽐如A依赖B时,创建A时候,就会先去创建B,// 当真正需要创建B时,就没必要再代理⼀次已经代理过的对象),避免重复创建Object cacheKey = getCacheKey(bean.getClass(), beanName);if (this.earlyProxyReferences.remove(cacheKey) != bean) {return wrapIfNecessary(bean, beanName, cacheKey);}}return bean;}
3 AbstractAutoProxyCreator#wrapIfNecessary
/**● Wrap the given bean if necessary, i.e. if it is eligible for being proxied.● @param bean the raw bean instance● @param beanName the name of the bean● @param cacheKey the cache key for metadata access● @return a proxy wrapping the bean, or the raw bean instance as-is*/protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {// targetSourcedBeans包含,说明前⾯创建过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.// 得到所有候选Advisor,对Advisors和bean的⽅法双层遍历匹配,最终得到⼀个List<Advisor>,即specificInterceptorsObject[] 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 AbstractAutoProxyCreator#createProxy
/**● Create an AOP proxy for the given bean.● 为指定 bean 创建代理对象*/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);}// 创建代理的⼯作交给ProxyFactoryProxyFactory proxyFactory = new ProxyFactory();proxyFactory.copyFrom(this);// 根据⼀些情况判断是否要设置proxyTargetClass=true(为true时强制使用Cglib动态代理)if (!proxyFactory.isProxyTargetClass()) {if (shouldProxyTargetClass(beanClass, beanName)) {proxyFactory.setProxyTargetClass(true);}else {evaluateProxyInterfaces(beanClass, proxyFactory);}}// 把指定和通⽤拦截对象合并, 并都适配成Advisor(AOP就是拦截器)Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);proxyFactory.addAdvisors(advisors);// 设置参数proxyFactory.setTargetSource(targetSource);customizeProxyFactory(proxyFactory);proxyFactory.setFrozen(this.freezeProxy);if (advisorsPreFiltered()) {proxyFactory.setPreFiltered(true);}// 上⾯准备做完就开始创建代理return proxyFactory.getProxy(getProxyClassLoader());}
5 ProxyFactory
接着跟进到ProxyFactory中
public class ProxyFactory extends ProxyCreatorSupport {public Object getProxy(ClassLoader classLoader) {// ⽤ProxyFactory创建AopProxy, 然后⽤AopProxy创建Proxy,// 所以这⾥重要的是看获取的AopProxy// 对象是什么,// 然后进去看怎么创建动态代理, 提供了两种:jdk proxy, cglibreturn createAopProxy().getProxy(classLoader);}}public class ProxyCreatorSupport extends AdvisedSupport {private AopProxyFactory aopProxyFactory;public ProxyCreatorSupport() {this.aopProxyFactory = new DefaultAopProxyFactory();}protected final synchronized AopProxy createAopProxy() {if (!this.active) {activate();}//先获取创建AopProxy的⼯⼚, 再由此创建AopProxyreturn getAopProxyFactory().createAopProxy(this);}public AopProxyFactory getAopProxyFactory() {return this.aopProxyFactory;}}
流程就是⽤AopProxyFactory创建AopProxy, 再⽤AopProxy创建代理对象,这⾥的AopProxyFactory默认是DefaultAopProxyFactory,看他的createAopProxy⽅法。
6 DefaultAopProxyFactory#createAopProxy
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {@Overridepublic 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()) {return new JdkDynamicAopProxy(config);}return new ObjenesisCglibAopProxy(config);} else {return new JdkDynamicAopProxy(config);}}/**● Determine whether the supplied {@link AdvisedSupport} has only the● {@link org.springframework.aop.SpringProxy} interface specified (or no* proxy interfaces specified at all).*/private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {Class<?>[] interfaces = config.getProxiedInterfaces();return (interfaces.length == 0 ||(interfaces.length == 1 && SpringProxy.class.equals(interfaces[0])));}}
这⾥决定创建代理对象是⽤JDK Proxy,还是⽤ Cglib 了,最简单的从使⽤⽅⾯使⽤来说:设置 proxyTargetClass=true强制使⽤Cglib 代理,什么参数都不设并且对象类实现了接⼝则默认⽤JDK 代理,如果没有实现接⼝则也必须⽤Cglib。
ProxyFactory#getProxy(java.lang.ClassLoader)——— CglibAopProxy#getProxy(java.lang.ClassLoader)
7 CglibAopProxy#getProxy
@Overridepublic Object getProxy(@Nullable ClassLoader classLoader) {if (logger.isTraceEnabled()) {logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());}try {Class<?> rootClass = this.advised.getTargetClass();Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");Class<?> proxySuperClass = rootClass;if (ClassUtils.isCglibProxyClass(rootClass)) {proxySuperClass = rootClass.getSuperclass();Class<?>[] additionalInterfaces = rootClass.getInterfaces();for (Class<?> additionalInterface : additionalInterfaces) {this.advised.addInterface(additionalInterface);}}// Validate the class, writing log messages as necessary.validateClassIfNecessary(proxySuperClass, classLoader);// 配置 Cglib 增强Enhancer enhancer = createEnhancer();if (classLoader != null) {enhancer.setClassLoader(classLoader);if (classLoader instanceof SmartClassLoader && ((SmartClassLoader)classLoader).isClassReloadable(proxySuperClass)) {enhancer.setUseCache(false);}}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 aboveenhancer.setCallbackFilter(new ProxyCallbackFilter(this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap,this.fixedInterceptorOffset));enhancer.setCallbackTypes(types);// ⽣成代理类,并且创建⼀个代理类的实例return createProxyClassAndInstance(enhancer, callbacks);} catch (CodeGenerationException | IllegalArgumentException ex) {throw new AopConfigException("Could not generate CGLIB subclass of "+ this.advised.getTargetClass() +": Common causes of this problem include using a final class or a non-visible class",ex);} catch (Throwable ex) {// TargetSource.getTarget() failedthrow new AopConfigException("Unexpected AOP exception", ex);}}
8 AOP源码分析类⽅法调⽤关系课堂讲解过程中记录
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean调⽤org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization调⽤org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization(后置处理器AbstractAutoProxyCreator完成bean代理对象创建)调⽤org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary调⽤org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy (在这⼀步把委托对象的aop增强和通⽤拦截进⾏合并,最终给代理对象)调⽤org.springframework.aop.framework.DefaultAopProxyFactory#createAopProxy调⽤org.springframework.aop.framework.CglibAopProxy#getProxy(java.lang.ClassLoader)
时序图
