Spring 中有一个接口非常重要:BeanPostProcessor,这个接口是对bean进行预处理的。
当spring解析bean的时候,在初始化受管bean之前,会调用所有实现了BeanPostProcessor接口的beandefinition的postProcessBeforeXXX方法。
初始化之后,会调用postProcesAfterXXX方法。
下面再来看AOP,都知道aop是通过生成代理类的方式来实现的,那么代理类是在什么时候生成的拿?原来,在
解析aop namespace配置文件的时候,spring自动生成了一个beandefinition:org.springframework.aop.config.internalAutoProxyCreator。
这个类继承了AbstractAutoProxyCreator,AbstractAutoProxyCreator则是继承了BeanPostProcessor的子类:SmartInstantiationAwareBeanPostProcessor,所以生成bean时,如果bean需要进行代理,则调用如下方法:
public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException { Object cacheKey = getCacheKey(beanClass, beanName); if(!targetSourcedBeans.contains(cacheKey)) { if(advisedBeans.contains(cacheKey) || nonAdvisedBeans.contains(cacheKey)) return null; if(isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { nonAdvisedBeans.add(cacheKey); return null; } } TargetSource targetSource = getCustomTargetSource(beanClass, beanName); if(targetSource != null) { targetSourcedBeans.add(beanName); Object specificInterceptors[] = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource); Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource); proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } else { return null; } }
protected Object createProxy(Class beanClass, String beanName, Object specificInterceptors[], TargetSource targetSource) { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.copyFrom(this); if(!shouldProxyTargetClass(beanClass, beanName)) { Class targetInterfaces[] = ClassUtils.getAllInterfacesForClass(beanClass, proxyClassLoader); Class aclass[]; int k = (aclass = targetInterfaces).length; for(int i = 0; i < k; i++) { Class targetInterface = aclass[i]; proxyFactory.addInterface(targetInterface); } } Advisor advisors[] = buildAdvisors(beanName, specificInterceptors); Advisor aadvisor[]; int l = (aadvisor = advisors).length; for(int j = 0; j < l; j++) { Advisor advisor = aadvisor[j]; proxyFactory.addAdvisor(advisor); } proxyFactory.setTargetSource(targetSource); customizeProxyFactory(proxyFactory); proxyFactory.setFrozen(freezeProxy); if(advisorsPreFiltered()) proxyFactory.setPreFiltered(true); return proxyFactory.getProxy(proxyClassLoader); }
至此, aop的内部实现基本分析过了。太细节的东西找时间再看。