Spring Bean 有 5 个作用域,但是最近有需求在多个地方获取同一个 Bean,只修改其中一个参数.那么 Bean 只在一个地方注入,修改属性就好,名字能一样吗?一系列问题
这个 StepScope 是什么鬼,5 个默认的 Scope 能满足需求吗?
Bean scopes
Scope | Description |
---|---|
singleton | Scopes a single bean definition to a single object instance per Spring IoC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. |
session | Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. |
global session | Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext. |
通常我们使用的是 singleton,默认也是.在测试中发现提供相同类型的 Bean,需要指定不同的 name 标识(@Bean("three")),使用时对应 @Qualifier("three").
疑问:经测试发现提供相同类型 Bean,不指定 Qualifier 会出错,但是在 SpringBatch 中指定了 @StepScope 却没报错,那是如何来区分应该在哪个 Step 中有效的呢?
通过查看 StepScope 文档 可以发现应该还有自定义 Scope 的存在来实现个性化需求,见 Bean scopes 之 4.4.5 Custom scopes.
参考
Spring 中 Bean 的作用域,生命周期 Spring 中 Bean 的五个作用域
来源: https://juejin.im/post/5a69390d6fb9a01cb80fea63