【Spring源码三千问】Bean的Scope有哪些?scope=request是什么原理?

前言

我们知道 Spring Bean 的 Scope 有多种类型:singleton、prototype、request、session。

Scope说明
singleton单例。每次注入都是同一个对象。
prototype多例。每次注入都是不同的对象。
request每个 request 请求,注入的都是不同的对象。(针对Web)
session每个 session,注入的都是不同的对象。(针对Web)
application同一个 application下,注入的都是相同的对象。(针对Web)

singleton 和 prototype 不难理解:
scope=singleton 类型的 bean 是放入了 Spring 的一级缓存的,每次注入的都是缓存中的对象,是同一个对象。
scope=prototype 类型的 bean,每次注入时,都去重新创建出一个 bean,每次注入的都是不同的对象。

那 scope=request 和 scope=session 是如何实现的呢?

要实现每个 request 都不同的话,我们猜想 @Autowired 注入的肯定是一个代理对象, 每次使用时,代理都会先去 request 中获取,获取不到时再去创建一个新的对象?

接下来,我们就分析一下源码,来一探究竟!

版本约定

Spring 5.3.9 (通过 SpringBoot 2.5.3 间接引入的依赖)

正文

Scope 接口的类图

scope

RequestScope 在哪里注册的?

WebApplicationContextUtils#registerWebApplicationScopes()

public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory,
			@Nullable ServletContext sc) {
    // 注册 RequestScope 和 SessionScope
    beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
    beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope());
    if (sc != null) {
        ServletContextScope appScope = new ServletContextScope(sc);
        beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
        // Register as ServletContext attribute, for ContextCleanupListener to detect it.
        sc.setAttribute(ServletContextScope.class.getName(), appScope);
    }

    beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
    beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
    beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
    beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
    if (jsfPresent) {
        FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
    }
}

上面的源码中,可以发现,ServletRequest、ServletResponse、HttpSession、WebRequest 都被注册成了 ResolvableDependency,所以,我们可以通过 @Autowired/@Resource 注入这些对象。
关于 ResolvableDependency 的讲解请戳:【Spring源码三千问】BeanDefinition注册、Bean注册、Dependency注册有什么区别?

Scope 在哪里生效的?

scope 生效的地方是在 bean 加载的时候,AbstractBeanFactory#doGetBean() 时生效的。如下图:
doGetBean
可以看出:

  1. scope=singleton 是单独的处理逻辑
  2. scope=prototype 是单独的处理逻辑
  3. 其他 scope 是另一套单独的处理逻辑,而且都使用了 prototype 的方式在处理

scope=singleton 产生的 bean 才会放入到 一级缓存中。scope=prototype或者其他 scope 类型的 bean 是不会放入到一级缓存中的。
也就是说,scope=prototype、request、session 等类型的 bean,每次被注入时,bean 对象都是重新产生的。
这是重点!!!要记住哦

除了 scope=singleton、prototype 是单独的处理逻辑之外,其他类型的 scope 都会通过 Scope#get() 来获取 bean

scope=request 的原理

scope=request 类型的 bean 会通过 RequestScope 来获取 bean 对象。

// AbstractRequestAttributesScope#get()
public Object get(String name, ObjectFactory<?> objectFactory) {
    RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
    Object scopedObject = attributes.getAttribute(name, getScope());
    if (scopedObject == null) {
        scopedObject = objectFactory.getObject();
        attributes.setAttribute(name, scopedObject, getScope());
        // Retrieve object again, registering it for implicit session attribute updates.
        // As a bonus, we also allow for potential decoration at the getAttribute level.
        Object retrievedObject = attributes.getAttribute(name, getScope());
        if (retrievedObject != null) {
            // Only proceed with retrieved object if still present (the expected case).
            // If it disappeared concurrently, we return our locally created instance.
            scopedObject = retrievedObject;
        }
    }
    return scopedObject;
}

可以看出,会先从 RequestAttributes 中获取 bean,如果获取不到,则会通过 ObjectFactory 去获取(其实就是走 createBean 的流程)
每次浏览器重新发起 request 之后,RequestAttributes 都会被清空后重新设置值,这样每次 request 获取到的都是不同的对象。

requestAttributesHolder 是 ThreadLocal 类型的,能够做到线程间的隔离

private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
			new NamedThreadLocal<>("Request attributes");

scope=request 用法举例

@Component
@Scope(value = SCOPE_REQUEST)
//@Scope(value = SCOPE_REQUEST, proxyMode= ScopedProxyMode.TARGET_CLASS)
public class RequestId {
  private String reqId;
  ......
}

测试程序:

@RestController
@SpringBootApplication
public class Application {
    @Autowired
    private RequestId requestId;
    @Autowired
    private RequestId requestId2;

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    }
    
    @GetMapping("/status")
    public String status() {
        String ri = ObjectUtils.identityToString(requestId)  + "@requestId:" + requestId.getReqId();
        String ri2 = ObjectUtils.identityToString(requestId2) + "@requestId:" + requestId2.getReqId();
        return ri + "<br/>" + ri2;
    }

}

启动时会报如下错误:

Caused by: org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'requestId': Scope 'request' is not active for the current thread; 
consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; 
nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? 
If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131) ~[spring-web-5.3.9.jar:5.3.9]

分析错误原因:
注入 RequestId 依赖时会直接调用 Scope#get() 来获取依赖对象,而启动时并没有 RequestAttributes 对象,所以会报错。

解决:
添加 @Scope 添加属性 proxyMode= ScopedProxyMode.TARGET_CLASS

访问 http://localhost:8080/status 的返回如下:

com.kvn.scope.RequestId$$EnhancerBySpringCGLIB$$15d18b96@67c69b03@requestId:1d6768c0-0ebb-4bbe-b094-06e2232b8585
com.kvn.scope.RequestId$$EnhancerBySpringCGLIB$$15d18b96@67c69b03@requestId:1d6768c0-0ebb-4bbe-b094-06e2232b8585

分析
添加了 proxyMode= ScopedProxyMode.TARGET_CLASS 之后,扫描出的 BeanDefinition 中的 class=ScopedProxyFactoryBean,而且是 isSingleton=true,会走单例的创建流程。
通过 ScopedProxyFactoryBean 产生的是一个代理 bean,不会触发 RequestId 的加载。只有第一次使用时,才会触发 bean 的加载。
所以,加上 scope 加上 proxyMode= ScopedProxyMode.TARGET_CLASS 之后,启动就会注入一个代理 bean,就没有问题了。
相当于延迟初始化了。

自定义 scope

Spring 还可以自定义 scope,可以通过 org.springframework.beans.factory.config.CustomScopeConfigurer 来处理。
很少用到这种场景,这里不做展开。
scope 需要先注册,再使用。还可以通过 ConfigurableBeanFactory#registerScope() 来进行注册。

小结

scope 生效的地方是在 bean 加载的时候,调用 AbstractBeanFactory#doGetBean() 时生效的。
scope 的处理分为了三类:

  1. scope=singleton 是单独的处理逻辑,产生的 bean 会放入一级缓存
  2. scope=prototype 是单独的处理逻辑,产生的 bean 不会放入缓存
  3. 其他 scope 是另一套单独的处理逻辑,而且它使用了 prototype 的方式在处理,产生的 bean 不会放入缓存

所以,只有 scope=singleton 类型的 bean 在任何地方注入的目标对象都是相同的。其他 scope 类型的 bean,每注入一次都会重新产生一个对象。

为什么说"注入的目标对象都是相同的",而不是说"注入的对象都是相同的"?
答:因为 scope=singleton 类型的 bean 有可能被 @Lazy 进行标记,这时注入的就是一个代理 bean。没有使用 @Lazy 的地方就可能不是代理 bean。
AOP 也会使 singleton 类型的 bean 产生代理。
这些情况下,注入的对象可能是不同的,但是注入的最底层的目标对象是相同的。


SpringIoC源码视频讲解:

课程地址
SpringIoC源码解读由浅入深https://edu.51cto.com/sd/68e86

如果本文对你有所帮助,欢迎点赞收藏!

源码测试工程下载:
老王读Spring IoC源码分析&测试代码下载
老王读Spring AOP源码分析&测试代码下载

公众号后台回复:下载IoC 或者 下载AOP 可以免费下载源码测试工程…

阅读更多文章,请关注公众号: 老王学源码
gzh


系列博文:
【老王读Spring IoC-0】Spring IoC 引入
【老王读Spring IoC-1】IoC 之控制反转引入
【老王读Spring IoC-2】IoC 之 BeanDefinition 扫描注册
【老王读Spring IoC-3】Spring bean 的创建过程
【老王读Spring IoC-4】IoC 之依赖注入原理
【老王读Spring IoC-5】Spring IoC 小结——控制反转、依赖注入

相关阅读:
【Spring源码三千问】@Resource 与 @Autowired 的区别
【Spring源码三千问】bean name 的生成规则
【Spring源码三千问】BeanDefinition详细分析
【Spring源码三千问】Spring 是怎样解决循环依赖问题的?
【Spring源码三千问】哪些循环依赖问题Spring解决不了?
【Spring源码三千问】@Lazy为什么可以解决特殊的循环依赖问题?
【Spring源码三千问】BeanDefinition注册、Bean注册、Dependency注册有什么区别?
【Spring源码三千问】Bean的Scope有哪些?scope=request是什么原理?
【Spring源码三千问】为什么要用三级缓存来解决循环依赖问题?二级缓存行不行?一级缓存行不行?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老王学源码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值