AOP开启注解 在使用注解@Aspect来进行AOP操作时,需要在xml中进行配置
1 2 <aop:aspectj-autoproxy />
创建BeanFactory时obtainFreshBeanFactory()在解析xml加载BeanDefinition中,执行parseBeanDefinitions方法进行解析发现其内有逻辑是
1 delegate.parseCustomElement(ele)
即进行自定义标签的解析,会去META-INF/spring.handlers中寻找对应的handler,该标签的namespace是http://www.springframework.org/schema/aop ,去spring.handlers中找到对应的记录
1 NamespaceHandler handler = this .readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
1 http\://www.springframework.org/schema/aop =org.springframework.aop.config.AopNamespaceHandler
还有一个配置是spring.schemas,以找到对应的xsd文件
1 http\://www.springframework.org/schema/aop/spring-aop-3.1.xsd =org/springframework/aop/config/spring-aop-3.1.xsd
然后执行该handler中的init方法
1 2 NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass); namespaceHandler.init();
即执行AopNamespaceHandler#init
AopNamespaceHandler#init 1 2 3 4 5 6 7 8 9 public void init () { registerBeanDefinitionParser("config" , new ConfigBeanDefinitionParser()); registerBeanDefinitionParser("aspectj-autoproxy" , new AspectJAutoProxyBeanDefinitionParser()); registerBeanDefinitionDecorator("scoped-proxy" , new ScopedProxyBeanDefinitionDecorator()); registerBeanDefinitionParser("spring-configured" , new SpringConfiguredBeanDefinitionParser()); }
这里可以看到aspectj-autoproxy,也就是说在配置文件中如果存在<aop:aspectj-autoproxy/>
就会使用AspectJAutoProxyBeanDefinitionParser进行解析,调用parse方法
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 35 36 37 38 39 40 class AspectJAutoProxyBeanDefinitionParser implements BeanDefinitionParser { @Override public BeanDefinition parse (Element element, ParserContext parserContext) { AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element); extendBeanDefinition(element, parserContext); return null ; } private void extendBeanDefinition (Element element, ParserContext parserContext) { BeanDefinition beanDef = parserContext.getRegistry().getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); if (element.hasChildNodes()) { addIncludePatterns(element, parserContext, beanDef); } } private void addIncludePatterns (Element element, ParserContext parserContext, BeanDefinition beanDef) { ManagedList<TypedStringValue> includePatterns = new ManagedList<TypedStringValue>(); NodeList childNodes = element.getChildNodes(); for (int i = 0 ; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if (node instanceof Element) { Element includeElement = (Element) node; TypedStringValue valueHolder = new TypedStringValue(includeElement.getAttribute("name" )); valueHolder.setSource(parserContext.extractSource(includeElement)); includePatterns.add(valueHolder); } } if (!includePatterns.isEmpty()) { includePatterns.setSource(parserContext.extractSource(element)); beanDef.getPropertyValues().add("includePatterns" , includePatterns); } } }
而在registerBeanPostProcessors(beanFactory)中会去进行注册BeanPostProcessor,在上面解析xml注册的AnnotationAwareAspectJAutoProxyCreator的结构还挺复杂,实现的重要的两个接口都标出来了,实现了BeanPostProcessor和BeanFactoryAware两个接口
在该registerBeanPostProcessors(beanFactory)方法中会找到beanFactory中所有BeanPostProcessor的类,然后获取到该类实例
1 2 3 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true , false ); BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
在获取bean的时候会创建bean,但是不要忘了该类还实现了一个BeanFactoryAware接口,在创建bean之后会进行初始化,也就会执行org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods方法
1 2 3 if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this ); }
这样就会执行AbstractAdvisorAutoProxyCreator#setBeanFactory,也没干什么事,就是给几个变量赋了个值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 @Override public void setBeanFactory (BeanFactory beanFactory) { super .setBeanFactory(beanFactory); if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { throw new IllegalArgumentException( "AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory); } initBeanFactory((ConfigurableListableBeanFactory) beanFactory); } protected void initBeanFactory (ConfigurableListableBeanFactory beanFactory) { super .initBeanFactory(beanFactory); if (this .aspectJAdvisorFactory == null ) { this .aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory); } this .aspectJAdvisorsBuilder = new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this .aspectJAdvisorFactory); }
进行处理 由于实现了BeanPostProcessor接口,在进行实例化bean的前后会调用该类的postProcessBeforeInitialization和postProcessAfterInitialization
这里AnnotationAwareAspectJAutoProxyCreator是继承的AbstractAutoProxyCreator类
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 35 36 37 38 39 40 41 42 43 44 45 46 @Override public Object postProcessBeforeInstantiation (Class<?> beanClass, String beanName) throws BeansException { Object cacheKey = getCacheKey(beanClass, beanName); if (beanName == null || !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 ; } } if (beanName != null ) { TargetSource targetSource = getCustomTargetSource(beanClass, beanName); if (targetSource != null ) { this .targetSourcedBeans.add(beanName); Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource); Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource); this .proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } } return null ; } @Override public Object postProcessAfterInitialization (Object bean, String beanName) throws BeansException { if (bean != null ) { Object cacheKey = getCacheKey(bean.getClass(), beanName); if (this .earlyProxyReferences.remove(cacheKey) != bean) { return wrapIfNecessary(bean, beanName, cacheKey); } } return bean; }
在创建bean的过程中调用了org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation来进行调用BeanPostProcessor接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 protected Object resolveBeforeInstantiation (String beanName, RootBeanDefinition mbd) { Object bean = null ; if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { Class<?> targetType = determineTargetType(beanName, mbd); if (targetType != null ) { bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (bean != null ) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null ); } return bean; }
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 26 27 28 29 30 protected Object wrapIfNecessary (Object bean, String beanName, Object cacheKey) { if (beanName != null && 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; }
getAdvicesAndAdvisorsForBean查找增强器 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 protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) { List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName); if (advisors.isEmpty()) { return DO_NOT_PROXY; } return advisors.toArray(); } protected List<Advisor> findEligibleAdvisors (Class<?> beanClass, String beanName) { List<Advisor> candidateAdvisors = findCandidateAdvisors(); List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); extendAdvisors(eligibleAdvisors); if (!eligibleAdvisors.isEmpty()) { eligibleAdvisors = sortAdvisors(eligibleAdvisors); } return eligibleAdvisors; } protected List<Advisor> findCandidateAdvisors () { List<Advisor> advisors = super .findCandidateAdvisors(); advisors.addAll(this .aspectJAdvisorsBuilder.buildAspectJAdvisors()); return advisors; }
createProxy创建代理 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 protected Object createProxy ( Class<?> beanClass, String beanName, 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); proxyFactory.setTargetSource(targetSource); customizeProxyFactory(proxyFactory); proxyFactory.setFrozen(this .freezeProxy); if (advisorsPreFiltered()) { proxyFactory.setPreFiltered(true ); } return proxyFactory.getProxy(getProxyClassLoader()); }
突然发现就创建个代理对象,spring考虑的是方方面面的,太强大了
何处调用的呢? 既然知道了AbstractAutoProxyCreator是BeanPostProcessor接口,那么就找到spring是在哪里调用的BeanPostProcessor。
是在createBean环节中的initializeBean初始化来进行调用的
1 2 3 4 5 6 7 Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null ) { exposedObject = initializeBean(beanName, exposedObject, mbd); } }
来看一下initializeBean初始化中调用了哪些
1 2 3 4 5 6 7 8 invokeAwareMethods(beanName, bean); applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); invokeInitMethods(beanName, wrappedBean, mbd); applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
可以看到有两个地方分别调用的BeanPostProcessor的postProcessBeforeInitialization方法、postProcessAfterInitialization方法,找到源头了
注意:
如果存在循环依赖的话,会在调用三级缓存中的ObjectFactory.getObject()进行aop代理,使得得到的早期对象是代理对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 protected Object getEarlyBeanReference (String beanName, RootBeanDefinition mbd, Object bean) { Object exposedObject = bean; if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); if (exposedObject == null ) { return null ; } } } } return exposedObject; }