Spring框架重点 梳理

  • Spring设计理念

       Spring这个一站式轻量级开源框架之所以流行,因为该框架把对象之间的依赖关系转而用配置文件管理,也就是 DI依

赖注入机制;而这个注入关系在IoC的容器中被管理,所谓IoC,被称为Inversion of Control,控制反转。指将对象的创建

权反转(交给)给Spring管理来实现程序的解耦。在Spring中核心组件有三个:Core、Context、Bean:

       在一场演出中,Bean好比是一个个的演员;Context就是其中的舞台背景;而Core就是演出需要的道具;只有这些拼

凑在一起才能使一场演出顺利进行。

       Context就是多个Bean关系的集合,也被称之为IoC容器,Core便作为用来 发现、建立、维护工具每个Bean之间的关

系所需要的一系列工具。

  • Bean组件

       Bean组件位于 org.springframework.beans包下,该包下的所有类主要涉及 Bean的定义、Bean的创建、Bean的解

析。

       Bean的创建是典型的工厂模式,BeanFactory作为顶级接口,有3个子类:ListableBeanFactory接口(表示这些

Bean是可列表的)、HierarchicalBeanFactory接口(表示这些Bean存在继承关系,有父Bean)、以及定义Bean的自

动装配规则的AutowireCapableBeanFactory接口;而最终的默认实现类为DefaultListableBeanFactory

       Bean的定义由BeanDefinition描述,当Spring成功解析定义的<bean />节点后,在Spring内部将转化为

BeanDefinition,此后的操作都将针对该对象进行。

       Bean的解析主要是对Spring中配置文件的解析。

  •  Context组件

       Context组件位于 org.springframework.context包下,ApplicationContext作为顶级接口,分别继承了BeanFactory的

子类及 ResourceLoader的子类,使其能够以Bean为运行主体,同时可访问到任何外部资源:

         ApplicationContext子类主要包含:ConfigurableApplicationContext及WebApplicationContext,前者用来动态添加

或修改已有配置信息,后者是为Web而准备的Context:

  • Core组件

        该组件一个重要的组成部分就是利用Resource接口定义了资源的访问方式,如下:

        Resource继承了InputStreamSource接口,在该接口中有个getInputStream方法,返回InputStream类,屏蔽了资源

的提供者; ResourceLoader接口屏蔽了资源加载者所带来的差异。

  • IoC 控制反转

        IoC容器实际上就是Context组件结合其他两个组件共同构建的一个Bean关系网,而构建的入口就是

AbstractApplicationContext中的refresh方法:

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

		// 1.刷新所有BeanFactory子容器.
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// 创建BeanFactory后,添加一些Spring本身需要的工具类
		prepareBeanFactory(beanFactory);

		try {
			// 功能扩展性-对已经构建的BeanFactory配置做一些修改
			postProcessBeanFactory(beanFactory);

			invokeBeanFactoryPostProcessors(beanFactory);

			//  功能扩展性-可再创建的Bean实例对象时添加一些自定义操作
			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();

			// 2.在BeanFactory进行Bean的实例化及Bean关系网的构建
			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();
		}
	}
}

/**
 * Tell the subclass to refresh the internal bean factory.
 * @return the fresh BeanFactory instance
 * @see #refreshBeanFactory()
 * @see #getBeanFactory()
 */
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	refreshBeanFactory();
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (logger.isDebugEnabled()) {
		logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
	}
	return beanFactory;
}

/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	
	... ...

	// Stop using the temporary ClassLoader for type matching.
	beanFactory.setTempClassLoader(null);

	// Allow for caching all bean definition metadata, not expecting further changes.
	beanFactory.freezeConfiguration();

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

         1. 根据可更新子类AbstractRefreshableApplicationContext中的refreshBeanFactory方法刷新所有BeanFactory子容

器,已存在BeanFactory则更新,否则新创建:

/**
 * This implementation performs an actual refresh of this context's underlying
 * bean factory, shutting down the previous bean factory (if any) and
 * initializing a fresh bean factory for the next phase of the context's lifecycle.
 */
@Override
protected final void refreshBeanFactory() throws BeansException {
	if (hasBeanFactory()) {
		destroyBeans();
		closeBeanFactory();
	}
	try {
		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);
	}
}

     2. 利用FactoryBean来进行Bean实例化:

@Override
public void preInstantiateSingletons() throws BeansException {
	if (this.logger.isDebugEnabled()) {
		this.logger.debug("Pre-instantiating singletons in " + this);
	}
	// Iterate over a copy to allow for init methods which in turn register new bean definitions.
	// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
	List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

	// Trigger initialization of all non-lazy singleton beans...
	for (String beanName : beanNames) {
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			if (isFactoryBean(beanName)) {
				final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
				boolean isEagerInit;
				if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
					isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
						@Override
						public Boolean run() {
							return ((SmartFactoryBean<?>) factory).isEagerInit();
						}
					}, getAccessControlContext());
				}
				else {
					isEagerInit = (factory instanceof SmartFactoryBean &&
							((SmartFactoryBean<?>) factory).isEagerInit());
				}
				if (isEagerInit) {
					getBean(beanName);
				}
			}
			else {
				getBean(beanName);
			}
		}
	}
	// Trigger post-initialization callback for all applicable beans...
	for (String beanName : beanNames) {
		Object singletonInstance = getSingleton(beanName);
		if (singletonInstance instanceof SmartInitializingSingleton) {
			final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
			if (System.getSecurityManager() != null) {
				AccessController.doPrivileged(new PrivilegedAction<Object>() {
					@Override
					public Object run() {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}
				}, getAccessControlContext());
			}
			else {
				smartSingleton.afterSingletonsInstantiated();
			}
		}
	}
}

      接口FactoryBean,是个工厂Bean,可以产生Bean实例的Bean,如果一个类继承或实现FactoryBean,则可以通过实

现getObject方法来自定义扩展Bean实例对象;Spring获取FactoryBean本身的对象可以通过在前面加上&来完成。

      详情可以参考:BeanFactory与FactoryBean的比较

  • IoC容器的扩展点

      1. org.springframework.beans.factory.config.BeanFactoryPostProcessor接口:构建BeanFactory时调用

      2. org.springframework.beans.factory.config.BeanPostProcessor接口:构建Bean对象时调用

      3. org.springframework.beans.factory.InitializingBean接口:Bean实例被创建时调用

      4. org.springframework.beans.factory.DisposableBean接口:Bean实例被销毁时调用

      5. org.springframework.beans.factory.FactoryBean接口:可以产生自定义Bean实例的Bean

      举例说明:若将IoC容器比作是一个箱子,箱子里有若干球模子,依据模子可造不同的球;还有一个可生产球模子的机

器,以及一个不是预先定型并且形状任意确定的神奇球模;关系如下:

  • Spring AOP

                未完待续。。。。

猜你喜欢

转载自blog.csdn.net/qq_39028580/article/details/81167729