Spring5学习-IoC容器


文章参考谭勇德老师的《Spring 5 核心原理与30个类手写实战》

我理解的IoC容器

IoC(Inversion of Control, 控制反转)

传统程序设计中软件系统的底层由多个对象构成,软件系统的功能由对象间的合作实现,在对象内部创建依赖对象,是程序主动创建,耦合度高。控制反转是将需要创建、依赖的对象反转给IoC容器实现,由容器帮我们查找、注入依赖对象,对象只是被动的接受依赖对象,同时需要一种描述让容器知道要创建的对象与目标对象间的关系,这个描述最具体的实现就是配置文件。

重要接口

BeanFactory

BeanFactory是最顶层的接口类,定义了IoC容器的基本功能规范,有三个重要子类:ListableBeanFactory、HierarchicalBeanFactory、AutowireCapableBeanFactory。最终的默认实现类是DefaultListableBeanFactory。

  • ListableBeanFactory接口表示这些Bean可以列表化。
  • HierarchicalBeanFactory接口表示这些Bean有继承关系。
  • AutowireCapableBeanFactory接口定义Bean的自动装配原则。

BeanDefinition

Bean对象在Spring中实现是以BeanDefinition来描述的,BeanDefinition定义了Bean对象的一些基本行为。配置文件中的标签和BeanDefinition中的属性是一一对应的。
BeanDefinition接口

BeanDefinitionReader

Bean的解析主要就是对Spring配置文件的解析,这个解析过程由BeanDefinitionReader完成,解析的结果是将Resource资源转换成BeanDefinition。
BeanDefinitionReader接口

ApplicationContext

Spring提供的一个高级IoC容器,继承了BeanFactory的基本功能,还提供以下服务:

  • 支持信息源,可实现国际化(实现MessageSource接口)。
  • 访问资源(实现ResourcePatternResolver接口)。
  • 支持应用事件(实现ApplicationEventPublisher接口)

ApplicationContext的子接口分为两个部分:

  • ConfigurableApplicationContext(大部分应用上下文都实现了该接口)
  • WebApplicationContext(Web应用程序中使用)

ApplicationContext的实现类有XmlWebApplicationContext、ClasspathXmlApplicationContext、FileSystemXmlApplicationContext等。

基于XML的IoC容器初始化

IoC容器初始化包括BeanDefinition的Resource定位、加载、注册三个基本过程。

入口,通过main()方法启动

ApplicationContext app = new ClassPathXmlApplicationContext("application.xml");

调用的构造函数如下:

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
		this(new String[] {configLocation}, true, null);
	}


public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);//调用父容器的构造方法为容器设置好Bean资源加载器
		setConfigLocations(configLocations);//设置Bean配置信息的定位路径
		if (refresh) {
			refresh();
		}
	}

开始启动

SpringIoC容器对配置资源的载入是从refresh()方法开始的。ClasspathXmlApplicationContext通过调用父类AbstractApplicationContext的refresh()方法启动整个IoC容器对Bean定义的载入过程。源码如下:

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

refresh()方法的主要作用是在创建IoC容器前,如果有容器存在,则销毁和关闭已有的容器,保证refresh()方法后使用的是新创建的IoC容器。

创建容器

AbstractApplicationContext类中只抽线定义了refreshBeanFactory()方法,容器真正调用的是其子类AbstractRefreshableApplicationContext中实现的refreshBeanFactory()方法,源码如下:

protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {//如果已经有容器,则销毁容器中的Bean,关闭容器
			destroyBeans();
			closeBeanFactory();
		}
		try {
		//创建IoC容器
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
			//调用载入Bean定义的方法
			loadBeanDefinitions(beanFactory);
			this.beanFactory = beanFactory;
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}

载入配置路径

AbstractRefreshableApplicationContext中只定义了抽象loadBeanDefinitions()方法,容器实际调用其子类AbstractXmlApplicationContext类中实现的loadBeanDefinitions()方法,源码如下:

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		beanDefinitionReader.setEnvironment(this.getEnvironment());
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// Allow a subclass to provide custom initialization of the reader,
		// then proceed with actually loading the bean definitions.
		initBeanDefinitionReader(beanDefinitionReader);
		//Bean读取器真正实现加载的方法
		loadBeanDefinitions(beanDefinitionReader);
	}

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		//获取Bean配置资源的位置
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
		//XmlBeanDefinitionReader调用其父类AbstractBeanDefinitionReader读取定位的Bean配置资源
			reader.loadBeanDefinitions(configResources);
		}
		//如果获取的Bean定位资源位置为空,则获取ClassPathXmlApplicationContext构造方法中setConfigLocations方法设置的资源
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			reader.loadBeanDefinitions(configLocations);
		}
	}

由于使用ClassPathXmlApplicationContext为例子,getConfigResources()方法的返回值为null,所以程序执行reader.loadBeanDefinitions(configLocations)分支。AbstractBeanDefinitionReader的loadBeanDefinition()方法源码如下:

public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(location, null);
	}

public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
		//获取IoC容器在初始化过程中创建的设置的资源加载器
		ResourceLoader resourceLoader = getResourceLoader();
		if (resourceLoader == null) {
			throw new BeanDefinitionStoreException(
					"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
		}

		if (resourceLoader instanceof ResourcePatternResolver) {
			// Resource pattern matching available.
			try {
			//加载多个指定位置的Bean配置信息
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
				//委派调用子类XmlBeanDefinitionReader的方法,实现加载功能
				int loadCount = loadBeanDefinitions(resources);
				if (actualResources != null) {
					for (Resource resource : resources) {
						actualResources.add(resource);
					}
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
				}
				return loadCount;
			}
			catch (IOException ex) {
				throw new BeanDefinitionStoreException(
						"Could not resolve bean definition resource pattern [" + location + "]", ex);
			}
		}
		else {
			//加载单个指定位置的Bean配置信息
			Resource resource = resourceLoader.getResource(location);
			//委派调用子类XmlBeanDefinitionReader的方法,实现加载功能
			int loadCount = loadBeanDefinitions(resource);
			if (actualResources != null) {
				actualResources.add(resource);
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
			}
			return loadCount;
		}
	}

可以看出AbstractBeanDefinitionReader的loadBeanDefinitions()方法做了两件事:

  1. resourceLoader.getResource(location),获取要加载的资源。
  2. 真正执行加载功能,由子类XmlBeanDefinitionReader的loadBeanDefinitions()方法完成。

解析配置文件路径

XmlBeanDefinitionReader调用ClasspathXmlApplicationContext的父类DefaultResourceLoader的getResource()方法获取要加载的资源。源码如下:

public Resource getResource(String location) {
		Assert.notNull(location, "Location must not be null");

		for (ProtocolResolver protocolResolver : this.protocolResolvers) {
			Resource resource = protocolResolver.resolve(location, this);
			if (resource != null) {
				return resource;
			}
		}

		//既不是类路径也不是URL标识的Resource定位
		if (location.startsWith("/")) {
			return getResourceByPath(location);
		}
		//类路径方式,使用ClassPathResource作为Bean文件的资源对象
		else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
			return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
		}
		else {
			try {
				// URL方式使用UrlResource作为Bean文件的资源对象
				URL url = new URL(location);
				return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
			}
			catch (MalformedURLException ex) {
				// No URL -> resolve as resource path.
				return getResourceByPath(location);
			}
		}
	}

开始读取配置内容

回到XmlBeanDefinitionReader的loadBeanDefinitions()方法

public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		//将读入的XML文件进行特殊编码处理
		return loadBeanDefinitions(new EncodedResource(resource));
	}

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
		Assert.notNull(encodedResource, "EncodedResource must not be null");
		if (logger.isInfoEnabled()) {
			logger.info("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 {
			//将资源文件转为InputStream的I/O流
			InputStream inputStream = encodedResource.getResource().getInputStream();
			try {
				//从InputStream中得到XML的解析源
				InputSource inputSource = new InputSource(inputStream);
				if (encodedResource.getEncoding() != null) {
					inputSource.setEncoding(encodedResource.getEncoding());
				}
				//具体的读取过程
				return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
			}
			finally {
				//关闭I/O流
				inputStream.close();
			}
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(
					"IOException parsing XML document from " + encodedResource.getResource(), ex);
		}
		finally {
			currentResources.remove(encodedResource);
			if (currentResources.isEmpty()) {
				this.resourcesCurrentlyBeingLoaded.remove();
			}
		}
	}

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {
		try {
			//将XML文件转换为DOM对象,解析过程由doLoadDocument()方法实现
			Document doc = doLoadDocument(inputSource, resource);
			//启动对Bean定义的详细解析过程
			return registerBeanDefinitions(doc, resource);
		}
		...
	}

protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
		return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
				getValidationModeForResource(resource), isNamespaceAware());
	}

准备文档对象

DocumentLoader接口中只定义了loadDocument()方法,具体实现在其子类DefaultDocumentLoader中,源码如下:

public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
			ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {

		//创建文档解析器工厂
		DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
		if (logger.isDebugEnabled()) {
			logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
		}
		//创建文档解析器
		DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
		//解析Spring的Bean配置信息
		return builder.parse(inputSource);
	}

protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
			throws ParserConfigurationException {

		//创建文档解析工厂
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(namespaceAware);

		//设置解析XML的校验
		if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
			factory.setValidating(true);
			if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
				// Enforce namespace aware for XSD...
				factory.setNamespaceAware(true);
				try {
					factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
				}
				catch (IllegalArgumentException ex) {
					ParserConfigurationException pcex = new ParserConfigurationException(
							"Unable to validate using XSD: Your JAXP provider [" + factory +
							"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
							"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
					pcex.initCause(ex);
					throw pcex;
				}
			}
		}

		return factory;
	}

至此Spring IoC容器根据定位的Bean配置信息将其读入并转换为文档对象完成。接下来将其解析成Spring IoC管理的Bean对象并注册到容器中。

分配解析策略

XmlBeanDefinitionReader类中的doLoadBeanDefinition()方法中调用registerBeanDefinitions()方法启动Spring IoC容器对Bean定义的解析过程。源码如下:

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		//得到BeanDefinitionDocumentReader来对文档对象进行解析
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		//获得容器中注册的Bean数量
		int countBefore = getRegistry().getBeanDefinitionCount();
		//具体的解析过程由DefaultBeanDefinitionDocumentReader完成
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

将配置载入内存

BeanDefinitionDocumentReader接口通过registerBeanDefinitions()方法调用实现类DefaultBeanDefinitionDocumentReader对文档对象进行解析,源码如下:

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		//获得XML描述符
		this.readerContext = readerContext;
		logger.debug("Loading bean definitions");
		//获得Document根元素
		Element root = doc.getDocumentElement();
		doRegisterBeanDefinitions(root);
	}

protected void doRegisterBeanDefinitions(Element root) {
		//具体的解析过程由BeanDefinitionParserDelegate实现
		BeanDefinitionParserDelegate parent = this.delegate;
		this.delegate = createDelegate(getReaderContext(), root, parent);

		if (this.delegate.isDefaultNamespace(root)) {
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isInfoEnabled()) {
						logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}

		preProcessXml(root);
		//从文档根元素开始进行Bean定义的文档对象的解析
		parseBeanDefinitions(root, this.delegate);
		postProcessXml(root);

		this.delegate = parent;
	}

//使用Spring的Bean规则从文档的根元素开始Bean定义的文档对象的解析
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		//Bean定义的文档对象使用了Spring默认的XML命名空间
		if (delegate.isDefaultNamespace(root)) {
			//获取Bean定义的文档对象根元素的所有子节点
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				//获取的文档节点是XML元素节点
				if (node instanceof Element) {
					Element ele = (Element) node;
					if (delegate.isDefaultNamespace(ele)) {
					//使用Spring的Bean规则解析元素节点
						parseDefaultElement(ele, delegate);
					}
					else {
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			delegate.parseCustomElement(root);
		}
	}

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		//如果节点是<import>导入元素,进行导入解析
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			importBeanDefinitionResource(ele);
		}
		//如果节点是<alias>别名元素,进行别名解析
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);
		}
		//如果节点是<bean>元素,按照Spring的Bean规则解析元素
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);
		}
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		//BeanDefinitionHolder 是对BeanDefinition的封装,即Bean定义的封装类
		//对文档对象中<bean>元素的解析由BeanDefinitionParserDelegate实现
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
				//向Spring IoC容器注册解析得到的Bean定义,这是Bean定义向IoC容器注册的入口				
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			//发送注册事件
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}

载入< bean >元素由BeanDefinitionParserDelegate的parseBeanDefinitionElement()方法实现。载入< property >元素由parsePropertyElements()方法实现。载入< property >子元素由BeanDefinitionParserDelegate的parsePropertySubElement()方法实现。
在解析< bean >元素的过程中没有创建和实例化Bean对象,只是创建了Bean对象的定义类BeanDefinition,将< bean >元素中的配置信息设置到BeanDefinition中作为记录,当依赖注入时才使用这些记录信息创建和实例化具体的Bean对象。

分配注册策略

BeanDefinitionReaderUtils的注册源码如下:

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

		// 获得解析的BeanDefinition的名称
		String beanName = definitionHolder.getBeanName();
		//向Spring IoC容器注册BeanDefinition
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
		// 如果解析的BeanDefinition有别名,向Spring IoC容器注册别名
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String alias : aliases) {
				registry.registerAlias(beanName, alias);
			}
		}
	}

当调用BeanDefinitionReaderUtils向Spring IoC容器注册解析的BeanDefinition时,真正完成注册功能的是DefaultListableBeanFactory。

向容器注册

DefaultListableBeanFactory中使用一个HashMap的集合对象存放Spring IoC容器中注册解析的BeanDefinition。

private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);

//向Spring IoC容器注册解析的BeanDefinition
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");

		//校验解析的BeanDefinition
		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		if (existingDefinition != null) {
			if (!isAllowBeanDefinitionOverriding()) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
						"': There is already [" + existingDefinition + "] bound.");
			}
			else if (existingDefinition.getRole() < beanDefinition.getRole()) {
				// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
				if (logger.isWarnEnabled()) {
					logger.warn("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.isInfoEnabled()) {
					logger.info("Overriding bean definition for bean '" + beanName +
							"' with a different definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			else {
				if (logger.isDebugEnabled()) {
					logger.debug("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) {
					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;
		}
		//检查是否已经注册过同名的BeanDefinition
		if (existingDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
		else if (isConfigurationFrozen()) {
			//重置所有已经注册过的BeanDefinition的缓存
			clearByTypeCache();
		}
	}

至此Bean配置信息已经被解析后注册到Spring IoC容器中管理起来了,完成了Spring IoC容器的初始化工作。现在Spring IoC容器中已经建立了所有Bean的配置信息,Bean定义信息已经可以使用,注册的Bean定义信息是Spring IoC容器控制反转的基础,正是有了这些信息,容器才可以进行依赖注入。

属性注入

三种方式:

1 构造器注入(别注入对象在构造器中声明依赖对象的参数列表)
2 Setter方法注入(为依赖对象提供相应的Setter方法,就可以通过该方法将依赖对象设置到被注入对象中)
3接口注入(需要别注入的对象实现不必要的接口,一般不使用)

构造注入和设值注入有几点不同:

  1. 设值注入支持绝大部分依赖注入,构造注入不支持绝大部分依赖注入。
  2. 设值注入不会重写构造方法的值,如果对一个变量同时采用构造注入和设值注入,那么构造注入将不能覆盖设值注入的值,因为构造方法只能在对象被创建的时候被调用。
  3. 设值注入不能保证某种依赖关系是否已经被注入,构造注入能。比如设值注入时参数出错导致出错,但构造注入要求传入的构造参数必须正确。
  4. 使用设值注入可以避免循环依赖,因为如果对象A和对象B相互依赖,对象A在被创建之前,对象B是不能被创建的,反之亦然。

Bean管理

Bean生命周期

Bean的生命周期分为5步:

  1. 通过构造器创建Bean实例(无参构造)
  2. 为Bean的属性设置值和对其他Bean引用(set方法)
  3. 调用Bean的初始化方法
  4. Bean可以使用了
  5. 当容器关闭时,调用Bean的销毁方法
    代码如下:
<bean id="student" class="com.zt.spring5.beans.Student" init-method="initMethod" destroy-method="destoryMethod">
     <property name="name" value="zhangzhuan"></property>
</bean>


package com.zt.spring5.beans;

public class Student {
    String name;

    public Student() {
        System.out.println("第一步 执行无参数构造创建bean实例");
    }

    public void setName(String name) {
        this.name = name;
        System.out.println("第二步 调用set方法设置属性值");
    }

    public void initMethod() {
        System.out.println("第三步 调用bean的初始化方法");
    }

    public void destoryMethod() {
        System.out.println("第五步 调用bean的销毁方法");
    }
}

package com.zt.spring5.test;

import com.zt.spring5.beans.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo1 {
    @Test
    public void test1() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Student student = context.getBean("student", Student.class);
        System.out.println("第四步 获取创建的bean实例对象");
        System.out.println(student);
        ((ClassPathXmlApplicationContext)context).close();
    }
}

输出

Bean的后置处理器-生命周期有7步

需要实现BeanPostProcessor接口
代码如下:

	<bean id="student" class="com.zt.spring5.beans.Student" init-method="initMethod" destroy-method="destoryMethod">
        <property name="name" value="zhangzhuan"></property>
    </bean>

    <!-- 配置后置处理器 -->
    <bean id="mybeanpost" class="com.zt.spring5.beans.MyBeanPost"></bean>

public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化前执行的方法");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之后执行的方法");
        return bean;
    }

其他代码部分不变,结果如下:
输出

自动装配(XML)

根据指定装配规则(属性名称或者属性类型)
按照属性名注入代码如下:

<bean id="teacher" class="com.zt.spring5.autowire.Teacher" autowire="byName"></bean>
<bean id="department" class="com.zt.spring5.autowire.Department"></bean>

public class Teacher {
    private Department department;

    public void setDepartment(Department department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "department=" + department +
                '}';
    }
}

public class Department {
    @Override
    public String toString() {
        return "Department{}";
    }
}

 @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Teacher teacher = context.getBean("teacher", Teacher.class);
        System.out.println(teacher);
    }

按照属性类型注入时,如果有同类型的多个依赖对象会出错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值