【Spring注解必知必会】@Scope注解源码解析

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第13天,点击查看活动详情

概述

@Scope注解想必大家都有所了解,但是很少使用。项目中大部分使用的都是默认值,单例模式。但是作为一个有追求的程序员,我们是有必要了解它底层的实现原理,可以加深我们对Spring Bean生命周期和作用域的理解。

注解简述

@Scope注解, 用来表示Spring中Bean的作用域范围,可以分为一下几种类型:

● singleton: 默认值,单例模式,在整个Spring IoC容器中,使用singleton定义的Bean将只有一个实例。

● prototype: 多实例模式,每次通过容器的getBean方法获取prototype定义的Bean时,都将产生一个新的Bean实例。

● request: 对于每次HTTP请求,使用request定义的Bean都将产生一个新实例,即每次HTTP请求将会产生不同的Bean实例。只有在Web应用中使用Spring时,该作用域才有效。

● session: 对于每次HTTP Session,使用session定义的Bean都将产生一个新实例。同样只有在Web应用中使用Spring时,该作用域才有效。

具体使用参考下面的文章【Spring注解必知必会】全面了解@Scope:

结论:

  1. 如果Bean是singleton类型,会在容器初始化的时候,实例化Bean对象,并且每次调用getBean获取到的Bean对象都是同一个, 伴随着Spring 容器关闭而消亡。
  2. 如果Bean是prototype类型,会在每次调用getBean方法的时候实例化Bean对象,销毁由GC决定。
  3. request、session等类型的bean,只有在web应用中生效。
  4. 默认不设置的情况下,Bean的类型都是singleton类型。

源码解析

整体思路

  1. 解析定义的Bean Class, 生成对应的BeanDefinition, BeanDefintion中定义了接口判断Bean的作用域scope。
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {

	void setScope(@Nullable String scope);

	@Nullable
	String getScope();

	boolean isSingleton();

	boolean isPrototype();

}
复制代码
  1. BeanDefintion根据scope属性判断Bean创建的逻辑,如果scope是singleton单例模式,直接实例化,如果scope是prototype多实例模式,每次getBean重新实例化,如果是其他类型,则采用另外的逻辑处理,由于不常用,本文不重点讨论。

解析Bean Class

  1. 容器在初始化 执行refresh方法时,最终会调用到ConfigurationClassPostProcessor类来扫描Bean Class。
  2. ConfigurationClassPostProcessor类实现了BeanDefinitionRegistryPostProcessor接口,扩展该接口,可以往BeanDefinition注册中心中添加BeanDefinition。而ConfigurationClassPostProcessor类其中一个作用就是解析@ComponentScan注解,扫描@Configuration、@Service、@Controller、@Repository和@Component注解并注册BeanDefinition。
  3. 最终调用 ClassPathBeanDefinitionScanner#doScan方法扫描获取容器中的Bean Class,恒诚BeanDefinition对象。

  1. 通过socpeMeataResolver解析器解析出scope属性,设置到BeanDefinition中。

  1. 处理scope中的代理属性

  1. 至此,就解析出scope类的Bean Definition。

创建Bean

上面是根据BeanDefinition获取Bean对象时候调用的堆栈信息,最终会调用到AbstractBeanFactory#doGetBean方法, 我们重点查看下该方法。

protected <T> T doGetBean(
			String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
			throws BeansException {
           
		String beanName = transformedBeanName(name);
		Object beanInstance;

		// 先从单例缓存池中获取Bean
		Object sharedInstance = getSingleton(beanName);
        // 如果Bean实例已经存在
		if (sharedInstance != null && args == null) {
			if (logger.isTraceEnabled()) {
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
			beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}
        // 如果缓存中不存在,则需要创建Bean实例
		else {
            
               ............
				// 如果BeanDefinition是singleton单例模式
				if (mbd.isSingleton()) {
                    // 创建Bean对象,同时会将新建的Bean对象放到缓存池中
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							// Explicitly remove instance from singleton cache: It might have been put there
							// eagerly by the creation process, to allow for circular reference resolution.
							// Also remove any beans that received a temporary reference to the bean.
							destroySingleton(beanName);
							throw ex;
						}
					});
					beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
                // 如果BeanDefinition是prototype多实例模式
				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
                        // 直接创建对象
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}
                // 如果不是singleton或者prototype类型,则采用下面的逻辑
				else {
					String scopeName = mbd.getScope();
					if (!StringUtils.hasLength(scopeName)) {
						throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
					}
					Scope scope = this.scopes.get(scopeName);
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
					}
					try {
						Object scopedInstance = scope.get(beanName, () -> {
							beforePrototypeCreation(beanName);
							try {
								return createBean(beanName, mbd, args);
							}
							finally {
								afterPrototypeCreation(beanName);
							}
						});
						beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new ScopeNotActiveException(beanName, scopeName, ex);
					}
				}
			}
			catch (BeansException ex) {
				beanCreation.tag("exception", ex.getClass().toString());
				beanCreation.tag("message", String.valueOf(ex.getMessage()));
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
			finally {
				beanCreation.end();
			}
		}
        // 适配处理
		return adaptBeanInstance(name, beanInstance, requiredType);
	}
复制代码

以上就是整个@Scope注解的实现原理。

总结

本文主要讲述了@Scope注解的实现原理,可以帮助大家从源码层面理解Bean的生命周期和作用域范围。

猜你喜欢

转载自juejin.im/post/7130235020790202381