欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring框架重点 梳理

程序员文章站 2022-03-12 17:09:52
...
  • 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为运行主体,同时可访问到任何外部资源:

Spring框架重点 梳理

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

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

Spring框架重点 梳理

  • Core组件

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

Spring框架重点 梳理

        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框架重点 梳理

  • Spring AOP

         Spring AOP基于动态代理实现,而动态代理要从JDK本身说起:JDK 1.8 的java.lang.reflect.Proxy类就是构造代理

类的入口;其newProxyInstance方法作为创建代理对象的方法,源码如下:

//参数1:ClassLoader用于加载代理类的Loader类,通常和被代理的类是同一个Loader类
//参数2:Interfaces是要被代理的接口
//参数3:InvocationHandler用于执行除被代理接口方法之外的用户自定义的操作,也是用户需要代理的最终目的;调用的目标方法都被代理到其invoke方法中。
public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,
    InvocationHandler h)throws IllegalArgumentException{
        
	Objects.requireNonNull(h);

	final Class<?>[] intfs = interfaces.clone();
	final SecurityManager sm = System.getSecurityManager();
	if (sm != null) {
		checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
	}
	/*
	 * Look up or generate the designated proxy class.
	 */
	Class<?> cl = getProxyClass0(loader, intfs);
	/*
	 * Invoke its constructor with the designated invocation handler.
	 */
	try {
		if (sm != null) {
			checkNewProxyPermission(Reflection.getCallerClass(), cl);
		}

		final Constructor<?> cons = cl.getConstructor(constructorParams);
		final InvocationHandler ih = h;
		if (!Modifier.isPublic(cl.getModifiers())) {
			AccessController.doPrivileged(new PrivilegedAction<Void>() {
				public Void run() {
					cons.setAccessible(true);
					return null;
				}
			});
		}
		return cons.newInstance(new Object[]{h});
	} catch (IllegalAccessException|InstantiationException e) {
		throw new InternalError(e.toString(), e);
	} catch (InvocationTargetException e) {
		Throwable t = e.getCause();
		if (t instanceof RuntimeException) {
			throw (RuntimeException) t;
		} else {
			throw new InternalError(t.toString(), t);
		}
	} catch (NoSuchMethodException e) {
		throw new InternalError(e.toString(), e);
	}
}
/**
 * a cache of proxy classes
 */
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
	proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

/**
 * Generate a proxy class.  Must call the checkProxyAccess method
 * to perform permission checks before calling this.
 */
private static Class<?> getProxyClass0(ClassLoader loader,Class<?>... interfaces) {
	if (interfaces.length > 65535) {
		throw new IllegalArgumentException("interface limit exceeded");
	}

	// If the proxy class defined by the given loader implementing
	// the given interfaces exists, this will simply return the cached copy;
	// otherwise, it will create the proxy class via the ProxyClassFactory
	return proxyClassCache.get(loader, interfaces);
}

          Proxy$ProxyClassFactory.class 该内部类源码如下:

/**
 * A factory function that generates, defines and returns the proxy class given
 * the ClassLoader and array of interfaces.
 */
private static final class ProxyClassFactory implements BiFunction<ClassLoader, Class<?>[], Class<?>>{
	// prefix for all proxy class names
	private static final String proxyClassNamePrefix = "$Proxy";

	// next number to use for generation of unique proxy class names
	private static final AtomicLong nextUniqueNumber = new AtomicLong();

	@Override
	public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

		Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
		for (Class<?> intf : interfaces) {
			/*
			 * Verify that the class loader resolves the name of this
			 * interface to the same Class object.
			 */
			Class<?> interfaceClass = null;
			try {
				interfaceClass = Class.forName(intf.getName(), false, loader);
			} catch (ClassNotFoundException e) {
			}
			if (interfaceClass != intf) {
				throw new IllegalArgumentException(
					intf + " is not visible from class loader");
			}
			/*
			 * Verify that the Class object actually represents an
			 * interface.
			 */
			if (!interfaceClass.isInterface()) {
				throw new IllegalArgumentException(interfaceClass.getName() + " is not an interface");
			}
			/*
			 * Verify that this interface is not a duplicate.
			 */
			if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
				throw new IllegalArgumentException("repeated interface: " + interfaceClass.getName());
			}
		}
		// package to define proxy class in
		String proxyPkg = null; 
		int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

		/*
		 * Record the package of a non-public proxy interface so that the
		 * proxy class will be defined in the same package.  Verify that
		 * all non-public proxy interfaces are in the same package.
		 */
		for (Class<?> intf : interfaces) {
			int flags = intf.getModifiers();
			if (!Modifier.isPublic(flags)) {
				accessFlags = Modifier.FINAL;
				String name = intf.getName();
				int n = name.lastIndexOf('.');
				String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
				if (proxyPkg == null) {
					proxyPkg = pkg;
				} else if (!pkg.equals(proxyPkg)) {
					throw new IllegalArgumentException("non-public interfaces from different packages");
				}
			}
		}

		if (proxyPkg == null) {
			// if no non-public proxy interfaces, use com.sun.proxy package
			proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
		}

		/*
		 * Choose a name for the proxy class to generate.
		 */
		long num = nextUniqueNumber.getAndIncrement();
		String proxyName = proxyPkg + proxyClassNamePrefix + num;

		/*
		 * Generate the specified proxy class.
		 */
		byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);
		try {
			return defineClass0(loader, proxyName,proxyClassFile, 0, proxyClassFile.length);
		} catch (ClassFormatError e) {
			/*
			 * A ClassFormatError here means that (barring bugs in the
			 * proxy class generation code) there was some other
			 * invalid aspect of the arguments supplied to the proxy
			 * class creation (such as virtual machine limitations
			 * exceeded).
			 */
			throw new IllegalArgumentException(e.toString());
		}
	}
}

       将以上Proxy创建代理对象的过程利用时序图表示如下:

Spring框架重点 梳理

         其实代理的目的就是在调用目标方法时可以转而执行InvocationHandler类的invoke方法,所以Spring AOP 的实现

关键就在于如何在InvocationHandler上进行自定义。

         Spring AOP 创建代理对象使用到继承了FactoryBean的子类ProxyFactoryBean 以及 JdkDynamicAopProxy:

Spring框架重点 梳理

Spring框架重点 梳理

               详情参考:五大框架工作原理——Spring

  • 设计模式——代理设计模式

          待续。。。

  • 设计模式——策略设计模式

          应用场景: 策略模式,顾名思义就是做某事的策略,编程上完成指定某个操作有很多方案,但在不同的环境下应根

据需要选择对应合适的方案。

          示例图:

Spring框架重点 梳理

                     Context:当时所处的环境,可根据自身条件选择不同的策略实现类来完成操作,持有一个策略Strategy实例

                                     的引用;创建具体策略对象的方法也可以由它完成。

                     Strategy:抽象的策略接口,定义每个策略实现类要实现的策略抽象方法。

                     ConcreteStrategy:具体的策略实现类,实现在Strategy中定义的抽象方法。

            在Spring中的应用示例:

                    Spring的代理方式包括 以上介绍的JDK动态代理 及 cglib代理,这两种方式的使用运用了策略设计模式,

如下图:    

Spring框架重点 梳理

                 该结构与标准的策略模式稍微有点不同,此处抽象策略是AopProxy接口;Cglib2AopProxy与

JdkDynamicAopProxy分别代表两种具体的策略实现类;Context角色是ProxyFactoryBean;根据条件来选择使用JDK

代理方式还是cglib方式。

                 另外三个类主要负责创建具体的策略对象,ProxyFactoryBean通过依赖的方法来关联具体策略对象并调用策

略对象的getProxy(ClassLoader loader)方法完成操作。

相关标签: Spring 4