Spring注入源码分析(一)

一、Spring核心

  • 依赖注入(Dependnecy Injection)
  • 面向切面编程(AOP)

二、三种注入方式

  • XML配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

	<!--xml配置包扫面-->
	<context:component-scan base-package="com.moon.springSource.config" />

	<!--xml注入bean-->
	<bean id="bean" class="com.moon.springSource.bean.Bean" />

</beans>
  • 注解配置
//通过注解注入
@Component
public class Entity {
    private String name;
}
  • JAVA配置
//这是一个配置类
@Configuration
//申明包扫描
@ComponentScan("com.moon.springSource.entity")
public class Config {

    @Bean
    public Xml xml(){
        return new Xml();
    }

}

三、流程分析

  • 使用ClassPathXmlApplicationContext进行分析,讲解三种注入当时流程
public class Main {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        for (String name : context.getBeanDefinitionNames()) {
            System.out.println(name);
        }

    }
}
  • 核心方法refresh()进行讲解
	@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// 准备工作
			prepareRefresh();

			// 核心 获取bean工厂方法。 加载所有的bean 得到一个Map<String, BeanDefinition>
			//	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			//工厂的准备方法
			prepareBeanFactory(beanFactory);

			try {
				// 不同的子类会执行这个方法
				postProcessBeanFactory(beanFactory);

				// 执行PostProcessors,  JAVA配置就在这里执行
				//org.springframework.context.annotation.internalConfigurationAnnotationProcessor
				//org.springframework.context.annotation.internalAutowiredAnnotationProcessor
				//org.springframework.context.annotation.internalCommonAnnotationProcessor
				//org.springframework.context.event.internalEventListenerProcessor
				invokeBeanFactoryPostProcessors(beanFactory);

				// 注册bean processors,在创建实例的时候执行
				registerBeanPostProcessors(beanFactory);

				// 初始化国家化
				initMessageSource();

				// 初始化广播
				initApplicationEventMulticaster();

				// 模板方法,回调
				onRefresh();

				// 注册监听器
				registerListeners();

				// 核心, 完成bean的实例化
				finishBeanFactoryInitialization(beanFactory);

				// 完成刷新,广播
				finishRefresh();
			}

我们主要对
①ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); =>得到Map<String, BeanDefinition> (XML方式和注解配置)
②invokeBeanFactoryPostProcessors(beanFactory)=>得到Map<String, BeanDefinition> (JAVA配置)
③finishBeanFactoryInitialization(beanFactory);=>实例化
进行分析,将对三种方式的注入源码的主要流程进行分析

四、obtainFreshBeanFactory()源码分析


	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		//刷新
		refreshBeanFactory();
		//获取
		return getBeanFactory();
	}
	
	
	protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			//创建return new DefaultListableBeanFactory(getInternalParentBeanFactory());
			//真是类型为DefaultListableBeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
			//核心,将bean载入
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}


	@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// 创建一个reader,将beanFactory传进去
		//this.registry = registry;beanFactory作为reader的一个属性registry 
		//reader 的真实类型是XmlBeanDefinitionReader
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
		beanDefinitionReader.setEnvironment(this.getEnvironment());
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
		initBeanDefinitionReader(beanDefinitionReader);
		//加载reader,说白了就是加载reader的属性registry,此时的reader就是 beanFactory
		loadBeanDefinitions(beanDefinitionReader);
	}

	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			reader.loadBeanDefinitions(configResources);
		}
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			//两种方式获取配置文件,最后使用reader读取配置文件(xml)
			//此时reader的registry属性就是beanFactroy
			reader.loadBeanDefinitions(configLocations);
		}
	}

	//经过一系列循环,进入这里
	public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
		ResourceLoader resourceLoader = getResourceLoader();
		if (resourceLoader == null) {
			throw new BeanDefinitionStoreException(
					"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
		}

		if (resourceLoader instanceof ResourcePatternResolver) {
			try {
				//加载xml得到resources 
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
				//核心, 加载资源
				int count = loadBeanDefinitions(resources);
				if (actualResources != null) {
					Collections.addAll(actualResources, resources);
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
				}
				return count;
			}
			catch (IOException ex) {
				throw new BeanDefinitionStoreException(
						"Could not resolve bean definition resource pattern [" + location + "]", ex);
			}
		}
		else {
			// Can only load single resources by absolute URL.
			Resource resource = resourceLoader.getResource(location);
			int count = loadBeanDefinitions(resource);
			if (actualResources != null) {
				actualResources.add(resource);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
			}
			return count;
		}
	}

	//reader的真实类型是XmlBeanDefinitionReader,进入这个类的方法
	public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
		Assert.notNull(encodedResource, "EncodedResource must not be null");
		if (logger.isTraceEnabled()) {
			logger.trace("Loading XML bean definitions from " + encodedResource);
		}

		Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
		if (currentResources == null) {
			currentResources = new HashSet<>(4);
			this.resourcesCurrentlyBeingLoaded.set(currentResources);
		}
		if (!currentResources.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}
		try {
			//将资源(xml)转化为一个流
			InputStream inputStream = encodedResource.getResource().getInputStream();
			try {
				//转化为InputSource
				InputSource inputSource = new InputSource(inputStream);
				if (encodedResource.getEncoding() != null) {
					inputSource.setEncoding(encodedResource.getEncoding());
				}
				//执行
				return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
			}
			finally {
				inputStream.close();
			}
		}
	}


	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
			//将资源(XML)最终转化为Document 对象
			Document doc = doLoadDocument(inputSource, resource);
			int count = registerBeanDefinitions(doc, resource);
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + count + " bean definitions from " + resource);
			}
			return count;
		}
	}
	
	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		//创建documentReader ,准别解析doc
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		int countBefore = getRegistry().getBeanDefinitionCount();
		//核心方法	参数,doc ,XmlReaderContext 
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

	//构造XmlReaderContext ,将reader本身也传进去,此时的reader.registry = beanFactroy
	//对于docReader来讲,readerContext.reader.registry  = beanFactroy
	public XmlReaderContext createReaderContext(Resource resource) {
		return new XmlReaderContext(resource, this.problemReporter, this.eventListener,
				this.sourceExtractor, this, getNamespaceHandlerResolver());
	}


	//经过一系列的转化,终于走到这一步
	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		if (delegate.isDefaultNamespace(root)) {
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				if (node instanceof Element) {
					Element ele = (Element) node;
					if (delegate.isDefaultNamespace(ele)) {
					    //默认标签(使用bean进行讲解)
						parseDefaultElement(ele, delegate);
					}
					else {
						//其他标签(使用<context:component-scan /> 进行讲解)
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			delegate.parseCustomElement(root);
		}
	}

总结一下,现在在docReader中,这个对象的readerContext.reader.registry = beanFactroy
首先讲一下最简单的普通标签

	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// 注册map,getReaderContext().getRegistry()
				//getReaderContext()得到readerContext
				//public final BeanDefinitionRegistry getRegistry() {return this.reader.getRegistry();}
				//getReaderContext().getRegistry()对应的值就是beanFactroy
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// Send registration event.
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}


	public static void registerBeanDefinition(
			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
			throws BeanDefinitionStoreException {

		// 获取名字
		String beanName = definitionHolder.getBeanName();
		//注册
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

		// Register aliases for bean name, if any.
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String alias : aliases) {
				registry.registerAlias(beanName, alias);
			}
		}
	}

	@Override
	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException {

		Assert.hasText(beanName, "Bean name must not be empty");
		Assert.notNull(beanDefinition, "BeanDefinition must not be null");

		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		//从map获取
		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		if (existingDefinition != null) {
			if (!isAllowBeanDefinitionOverriding()) {
				throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
			}
			else if (existingDefinition.getRole() < beanDefinition.getRole()) {
				// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
				if (logger.isInfoEnabled()) {
					logger.info("Overriding user-defined bean definition for bean '" + beanName +
							"' with a framework-generated bean definition: replacing [" +
							existingDefinition + "] with [" + beanDefinition + "]");
				}
			}
			else if (!beanDefinition.equals(existingDefinition)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Overriding bean definition for bean '" + beanName +
							"' with a different definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Overriding bean definition for bean '" + beanName +
							"' with an equivalent definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			this.beanDefinitionMap.put(beanName, beanDefinition);
		}
		else {
			if (hasBeanCreationStarted()) {
				// Cannot modify startup-time collection elements anymore (for stable iteration)
				synchronized (this.beanDefinitionMap) {
					//核心
					//核心
					//核心
					//核心
					//核心
					//在map没有值得情况下就在beanFactroy对象的beanDefinitionMap属性中put,对象名称和详细信息
					this.beanDefinitionMap.put(beanName, beanDefinition);
					List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
					updatedDefinitions.addAll(this.beanDefinitionNames);
					updatedDefinitions.add(beanName);
					this.beanDefinitionNames = updatedDefinitions;
					if (this.manualSingletonNames.contains(beanName)) {
						Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
						updatedSingletons.remove(beanName);
						this.manualSingletonNames = updatedSingletons;
					}
				}
			}
			else {
				// Still in startup registration phase
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				this.manualSingletonNames.remove(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (existingDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
	}

注意:到这里,一个bean的就map的形式放在bean工厂里面,还没有实例化,只是存了所有信息
到这里通过xml的方式将java对象,转为map就完了。实际上就做了一件事,就是讲xml的配置转化为map,问题来了,注解配置和JAVA配置是怎么转化为map的
使用注解首先需要配置包扫描,扫描后才有效,下面我们一起来看一下xml中的其他标签<context:component-scan />,通过这个标签讲解注解注入和JAVA配置

	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		if (delegate.isDefaultNamespace(root)) {
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				if (node instanceof Element) {
					Element ele = (Element) node;
					if (delegate.isDefaultNamespace(ele)) {
						parseDefaultElement(ele, delegate);
					}
					else {
						//我们走第一条路线,其他的标签
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			delegate.parseCustomElement(root);
		}
	}

	@Nullable
	public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
		//获取这个http://www.springframework.org/schema/context,没有这个其他标签不能使用
		String namespaceUri = getNamespaceURI(ele);
		if (namespaceUri == null) {
			return null;
		}
		//不同的标签选择不同的处理器
		NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
		if (handler == null) {
			error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
			return null;
		}
		//解析
		return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
	}

public interface BeanDefinitionParser {
	@Nullable
	//解析方法
	BeanDefinition parse(Element element, ParserContext parserContext);

}


	//选择ComponentScanBeanDefinitionParser类进行处理
	@Override
	@Nullable
	public BeanDefinition parse(Element element, ParserContext parserContext) {
		String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
		basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
		String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
				ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

		// 获取scanner 
		ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
		//扫描包,这个时候将获取所有的beanDefinitions详细信息,都是扫描出来的
		//包括@Component, @Service, @Controller直接入住 和 @Configuration配置类
		Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
		registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

		return null;
	}



	protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
		Assert.notEmpty(basePackages, "At least one base package must be specified");
		Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
		//多个包进行循环
		for (String basePackage : basePackages) {
			//通过包找到BeanDefinition进行循环
			Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
			for (BeanDefinition candidate : candidates) {
				ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
				candidate.setScope(scopeMetadata.getScopeName());
				String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
				if (candidate instanceof AbstractBeanDefinition) {
					postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
				}
				if (candidate instanceof AnnotatedBeanDefinition) {
					AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
				}
				//检查名字存在
				if (checkCandidate(beanName, candidate)) {
					BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
					definitionHolder =
							AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
					beanDefinitions.add(definitionHolder);
					//很熟悉的感觉,注册到map
					registerBeanDefinition(definitionHolder, this.registry);
				}
			}
		}
		return beanDefinitions;
	}

目前,我们已经将xml中的bean转化为map了,已经用过包扫描将注解的形式注入的类转化为map,在扫描的过程中,我们也同是扫描了@Configuration的配置类,现在就差JAVA配置方式的bean还没有转化为map,我们来看下一个方法,JAVA配置

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值