Spring的@Scope注解详细解析

 更新时间:2023年11月24日 10:09:10   作者:baidu_25504651  
这篇文章主要介绍了Spring的@Scope注解详细解析,@Scope注解主要作用是调节Ioc容器中的作用域,springboot 程序启动时会对classpath路径下的包中的类进行扫描,将类解析成BeanDefinition,需要的朋友可以参考下

@Scope是什么,有什么用?

@Scope注解主要作用是调节Ioc容器中的作用域,在Spring IoC容器中主要有以下五种作用域:

基本作用域:singleton(单例)、prototype(多例);Web 作用域(reqeust、session、globalsession),自定义作用域。

@Scope注解源码解析

使用@Scope注解对象注入到IOC容器过程

(1) springboot 程序启动时会对classpath路径下的包中的类进行扫描,将类解析成BeanDefinition,在扫描完BeanDefinition后会对其进行注册,便于后面创建Bean时使用

    // org.springframework.context.annotation.ClassPathBeanDefinitionScanner#doScan	
    /**
	 * Perform a scan within the specified base packages,
	 * returning the registered bean definitions.
	 * <p>This method does <i>not</i> register an annotation config processor
	 * but rather leaves this up to the caller.
	 * @param basePackages the packages to check for annotated classes
	 * @return set of beans registered if any for tooling registration purposes (never {@code 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) {
			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);
					registerBeanDefinition(definitionHolder, this.registry);
				}
			}
		}
		return beanDefinitions;
	}

(2)接着会对扫描出来的BeanDefinition处理,其中下面代码对扫描完的Bean的作用域的代理模式进行处理:

 
    // org.springframework.context.annotation.AnnotationConfigUtils#applyScopedProxyMode	
    static BeanDefinitionHolder applyScopedProxyMode(
            ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) {
        ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode();
        if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
            return definition;
        }
        boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
        return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
    }

上面代码会判断作用域的代码模式,如果是ScopedProxyMode.NO,不进行代理处理直接返回BeanDefinition,如果不是NO,再判断是否是ScopedProxyMode.TARGET_CLASS,在后续逻辑中会根据此来决定是否创建目标类的代理类。

// org.springframework.aop.scope.ScopedProxyUtils#createScopedProxy	
public static BeanDefinitionHolder createScopedProxy(BeanDefinitionHolder definition,
			BeanDefinitionRegistry registry, boolean proxyTargetClass) {
		String originalBeanName = definition.getBeanName();
		BeanDefinition targetDefinition = definition.getBeanDefinition();
		String targetBeanName = getTargetBeanName(originalBeanName);
		// Create a scoped proxy definition for the original bean name,
		// "hiding" the target bean in an internal target definition.
		RootBeanDefinition proxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class);
		proxyDefinition.setDecoratedDefinition(new BeanDefinitionHolder(targetDefinition, targetBeanName));
		proxyDefinition.setOriginatingBeanDefinition(targetDefinition);
		proxyDefinition.setSource(definition.getSource());
		proxyDefinition.setRole(targetDefinition.getRole());
		proxyDefinition.getPropertyValues().add("targetBeanName", targetBeanName);
		if (proxyTargetClass) {
			targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
			// ScopedProxyFactoryBean's "proxyTargetClass" default is TRUE, so we don't need to set it explicitly here.
		}
		else {
			proxyDefinition.getPropertyValues().add("proxyTargetClass", Boolean.FALSE);
		}
		// Copy autowire settings from original bean definition.
		proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
		proxyDefinition.setPrimary(targetDefinition.isPrimary());
		if (targetDefinition instanceof AbstractBeanDefinition) {
			proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
		}
		// The target bean should be ignored in favor of the scoped proxy.
		targetDefinition.setAutowireCandidate(false);
		targetDefinition.setPrimary(false);
		// Register the target bean as separate bean in the factory.
		registry.registerBeanDefinition(targetBeanName, targetDefinition);
		// Return the scoped proxy definition as primary bean definition
		// (potentially an inner bean).
		return new BeanDefinitionHolder(proxyDefinition, originalBeanName, definition.getAliases());
	}

上面过程向BeanDefinitionRegistry中注入了两个BeanDefinition分别是目标类、目标类的代理类(beanClass为ScopedProxyFactoryBean.class)。

最终返回BeanDefinitionHolder的beanName为目标类名,beanClass为ScopedProxyFactoryBean.class的BeanDenifition。

return new BeanDefinitionHolder(proxyDefinition, originalBeanName, definition.getAliases());

其中ScopedProxyFactoryBean类实现了BeanFactoryAware,Aware接口由Spring在AbstractAutowireCapableBeanFactory.initializeBean(beanName, bean,mbd)方法中通过调用invokeAwareMethods(beanName, bean)方法和applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName)触发Aware方法的调用setBeanFactory方法,该方法中会创建一个目前类的代理类暂存在其proxy变量中。

// org.springframework.aop.scope.ScopedProxyFactoryBean#setBeanFactory
@Override
public void setBeanFactory(BeanFactory beanFactory) {
   if (!(beanFactory instanceof ConfigurableBeanFactory)) {
      throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
   }
   ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory;
   this.scopedTargetSource.setBeanFactory(beanFactory);
   ProxyFactory pf = new ProxyFactory();
   pf.copyFrom(this);
   pf.setTargetSource(this.scopedTargetSource);
   Assert.notNull(this.targetBeanName, "Property 'targetBeanName' is required");
   Class<?> beanType = beanFactory.getType(this.targetBeanName);
   if (beanType == null) {
      throw new IllegalStateException("Cannot create scoped proxy for bean '" + this.targetBeanName +
            "': Target type could not be determined at the time of proxy creation.");
   }
   if (!isProxyTargetClass() || beanType.isInterface() || Modifier.isPrivate(beanType.getModifiers())) {
      pf.setInterfaces(ClassUtils.getAllInterfacesForClass(beanType, cbf.getBeanClassLoader()));
   }
   // Add an introduction that implements only the methods on ScopedObject.
   ScopedObject scopedObject = new DefaultScopedObject(cbf, this.scopedTargetSource.getTargetBeanName());
   pf.addAdvice(new DelegatingIntroductionInterceptor(scopedObject));
   // Add the AopInfrastructureBean marker to indicate that the scoped proxy
   // itself is not subject to auto-proxying! Only its target bean is.
   pf.addInterface(AopInfrastructureBean.class);
   this.proxy = pf.getProxy(cbf.getBeanClassLoader());
}

在注入目标对象时,将会时用beanName从BeanDefinitionRegistry中取出beanclass为ScopedProxyFactoryBean.class的BeanDenifition,使用该BeanDenifition创建一个实例,创建完实例后会调用getObjectForBeanInstance方法来获取beanInstance,如果时FactoryBean则会调用其getObject()方法。

// org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean				
// Create bean instance.
				if (mbd.isSingleton()) {
					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);
				}
// org.springframework.beans.factory.support.AbstractBeanFactory#getObjectForBeanInstance	
	protected Object getObjectForBeanInstance(
			Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
		// Don't let calling code try to dereference the factory if the bean isn't a factory.
		if (BeanFactoryUtils.isFactoryDereference(name)) {
			if (beanInstance instanceof NullBean) {
				return beanInstance;
			}
			if (!(beanInstance instanceof FactoryBean)) {
				throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
			}
			if (mbd != null) {
				mbd.isFactoryBean = true;
			}
			return beanInstance;
		}
		// Now we have the bean instance, which may be a normal bean or a FactoryBean.
		// If it's a FactoryBean, we use it to create a bean instance, unless the
		// caller actually wants a reference to the factory.
		if (!(beanInstance instanceof FactoryBean)) {
			return beanInstance;
		}
		Object object = null;
		if (mbd != null) {
			mbd.isFactoryBean = true;
		}
		else {
			object = getCachedObjectForFactoryBean(beanName);
		}
		if (object == null) {
			// Return bean instance from factory.
			FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
			// Caches object obtained from FactoryBean if it is a singleton.
			if (mbd == null && containsBeanDefinition(beanName)) {
				mbd = getMergedLocalBeanDefinition(beanName);
			}
			boolean synthetic = (mbd != null && mbd.isSynthetic());
			object = getObjectFromFactoryBean(factory, beanName, !synthetic);
		}
		return object;
	}

 目标类会被解析成ScopedProxyFactoryBean,而ScopedProxyFactoryBean是FactoryBean,所以会调用ScopedProxyFactoryBean的getObject方法,而ScopedProxyFactoryBean的getObject方法返回的是其属性proxy即创建的目标类的代理类,

	@Override
	public Object getObject() {
		if (this.proxy == null) {
			throw new FactoryBeanNotInitializedException();
		}
		return this.proxy;
	}

到此这篇关于Spring的@Scope注解详细解析的文章就介绍到这了,更多相关@Scope注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • idea 无法debug调试的解决方案

    idea 无法debug调试的解决方案

    这篇文章主要介绍了idea 无法debug调试的解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Spring @async方法如何添加注解实现异步调用

    Spring @async方法如何添加注解实现异步调用

    这篇文章主要介绍了Spring @async方法如何添加注解实现异步调用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • Redis打开rdb文件常用方法详解

    Redis打开rdb文件常用方法详解

    这篇文章主要介绍了Redis打开rdb文件常用方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • java通过模拟post方式提交表单实现图片上传功能实例

    java通过模拟post方式提交表单实现图片上传功能实例

    这篇文章主要介绍了java通过模拟post方式提交表单实现图片上传功能实例,涉及Java针对表单的提交操作响应及文件传输的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-11-11
  • Java并发编程必备之Synchronized关键字深入解析

    Java并发编程必备之Synchronized关键字深入解析

    本文我们深入探索了Java中的Synchronized关键字,包括其互斥性和可重入性的特性,文章详细介绍了Synchronized的三种使用方式:修饰代码块、修饰普通方法和修饰静态方法,感兴趣的朋友一起看看吧
    2025-04-04
  • Java多线程之 FutureTask:带有返回值的函数定义和调用方式

    Java多线程之 FutureTask:带有返回值的函数定义和调用方式

    这篇文章主要介绍了Java多线程之 FutureTask:带有返回值的函数定义和调用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Flink状态和容错源码解析

    Flink状态和容错源码解析

    这篇文章主要为大家介绍了Flink状态和容错源码示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • java中Map集合的常用方法总结大全

    java中Map集合的常用方法总结大全

    开发中最常用的就是List集合和Map集合,Map集合是基于java核心类java.util中的,下面这篇文章主要给大家总结介绍了关于java中Map集合的一些常用方法,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-01-01
  • HashMap确定key的存储位置的源码分析

    HashMap确定key的存储位置的源码分析

    HashMap 作为 Java 中最常用的数据结构之一,用于存储和管理键值对,HashMap 基于哈希函数实现,能通过将 key 映射到特定的位置来实现快速存储、查找和删除数据,接下来将从源码角度分析以通俗易懂的方式向大家讲解一下 HashMap 如何确定 key 的存储位置的
    2023-07-07
  • Spring Boot结合IDEA自带Maven插件如何快速切换profile

    Spring Boot结合IDEA自带Maven插件如何快速切换profile

    IDEA是目前 Java 开发者中使用最多的开发工具,它有着简约的设计风格,强大的集成工具,便利的快捷键,这篇文章主要介绍了Spring Boot结合IDEA自带Maven插件快速切换profile,需要的朋友可以参考下
    2023-03-03

最新评论