通过之前的代码,我们知道spring代理生成是在对象实例化后并初始化后通过 BeanPostProcessor 机制来实现的
BeanPostProcessor注册
完成 AOP 相关的 BeanPostProcessor注册是在解析对应标签的时候(这里以配置文件为讲解对象,注解方式核心是一样的),处理aop对应的 NamespaceHandler 是
org.springframework.aop.config.AopNamespaceHandler
public class AopNamespaceHandler extends NamespaceHandlerSupport { /** * Register the {@link BeanDefinitionParser BeanDefinitionParsers} for the * '<code>config</code>', '<code>spring-configured</code>', '<code>aspectj-autoproxy</code>' * and '<code>scoped-proxy</code>' tags. */ public void init() { // In 2.0 XSD as well as in 2.1 XSD. registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser()); registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser()); registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator()); // Only in 2.0 XSD: moved to context namespace as of 2.1 registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser()); } }
解析标签的时候会调用 ConfigBeanDefinitionParser 的parse方法
public BeanDefinition parse(Element element, ParserContext parserContext) { CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); parserContext.pushContainingComponent(compositeDef); configureAutoProxyCreator(parserContext, element); List<Element> childElts = DomUtils.getChildElements(element); for (Element elt: childElts) { String localName = parserContext.getDelegate().getLocalName(elt); if (POINTCUT.equals(localName)) { parsePointcut(elt, parserContext); } else if (ADVISOR.equals(localName)) { parseAdvisor(elt, parserContext); } else if (ASPECT.equals(localName)) { parseAspect(elt, parserContext); } } parserContext.popAndRegisterContainingComponent(); return null; }
跟踪我标记的方法,最后会来到
org.springframework.aop.config.AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(ParserContext, Element)
public static void registerAspectJAutoProxyCreatorIfNecessary( ParserContext parserContext, Element sourceElement) { BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAutoProxyCreatorIfNecessary( parserContext.getRegistry(), parserContext.extractSource(sourceElement)); useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement); registerComponentIfNecessary(beanDefinition, parserContext); }
这个beanDefinition返回的是 AspectJAwareAdvisorAutoProxyCreator,而AspectJAwareAdvisorAutoProxyCreator是最终实现了BeanPostProcessor了的;
下面的代码也就是把这个beanDefinition注册进容器中,待后续实例化成beanPostprocessor后用于对我们的业务类进行处理;
代理生成
spring生成对象后会调用如下代码
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(Object, String)
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) { result = beanProcessor.postProcessAfterInitialization(result, beanName); if (result == null) { return result; } } return result; }
其中实现aop的BeanPostProcessor的类是AbstractAutoProxyCreator,其定义是:
public abstract class AbstractAutoProxyCreator extends ProxyConfig implements SmartInstantiationAwareBeanPostProcessor, BeanClassLoaderAware, BeanFactoryAware, Ordered, AopInfrastructureBean {
再看看
SmartInstantiationAwareBeanPostProcessor
public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
InstantiationAwareBeanPostProcessor 定义:
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
这里终于看到了期待已久的 BeanPostProcessor
下面就是生成代理类的调用链了:
at org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(DefaultAopProxyFactory.java:67) at org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy(ProxyCreatorSupport.java:104) at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:476) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
接下来看看
AbstractAutoProxyCreator是怎么生成代理对象的,其中重要的一点是决策用什么机制来生成代理对象,是用JDK提供的代理生产机制呢还是aspectJ,看如下代码
org.springframework.aop.framework.ProxyFactory.getProxy()
@SuppressWarnings("unchecked") public Object getProxy() { return createAopProxy().getProxy(); }
org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy()
/** * Subclasses should call this to get a new AOP proxy. They should <b>not</b> * create an AOP proxy with <code>this</code> as an argument. */ protected final synchronized AopProxy createAopProxy() { if (!this.active) { activate(); } return getAopProxyFactory().createAopProxy(this); }
org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(AdvisedSupport)
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()) { return new JdkDynamicAopProxy(config); } if (!cglibAvailable) { throw new AopConfigException( "Cannot proxy target class because CGLIB2 is not available. " + "Add CGLIB to the class path or specify proxy interfaces."); } return CglibProxyFactory.createCglibProxy(config); } else { return new JdkDynamicAopProxy(config); } }
这个方法主要功能决定了用那种方式来生产
AopProxy,进而在获得代理对象 Proxy
接下来的流程可以参看:
http://blog.csdn.net/linuu/article/details/50977614