Skip to content

Commit 7aa862f

Browse files
committed
Make scope fully configurable
Closes gh-36171
1 parent 2d2809f commit 7aa862f

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

spring-beans/src/main/java/org/springframework/beans/factory/BeanRegistry.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,13 @@ interface Spec<T> {
207207
*/
208208
Spec<T> prototype();
209209

210+
/**
211+
* Configure this bean with a custom scope.
212+
* @since 7.0.4
213+
* @see BeanDefinition#setScope(String)
214+
*/
215+
Spec<T> scope(String scope);
216+
210217
/**
211218
* Set the supplier to construct a bean instance.
212219
* @see AbstractBeanDefinition#setInstanceSupplier(Supplier)

spring-beans/src/main/java/org/springframework/beans/factory/support/BeanRegistryAdapter.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,12 @@ public Spec<T> prototype() {
279279
return this;
280280
}
281281

282+
@Override
283+
public Spec<T> scope(String scope) {
284+
this.beanDefinition.setScope(scope);
285+
return this;
286+
}
287+
282288
@Override
283289
public Spec<T> supplier(Function<SupplierContext, T> supplier) {
284290
this.beanDefinition.setInstanceSupplier(() ->

spring-beans/src/test/java/org/springframework/beans/factory/support/BeanRegistryAdapterTests.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,14 @@ void prototypeScope() {
186186
assertThat(beanDefinition.getScope()).isEqualTo(AbstractBeanDefinition.SCOPE_PROTOTYPE);
187187
}
188188

189+
@Test
190+
void customScope() {
191+
BeanRegistryAdapter adapter = new BeanRegistryAdapter(this.beanFactory, this.beanFactory, this.env, ScopeBeanRegistrar.class);
192+
new ScopeBeanRegistrar().register(adapter, env);
193+
BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition("foo");
194+
assertThat(beanDefinition.getScope()).isEqualTo("custom");
195+
}
196+
189197
@Test
190198
void defaultSupplier() {
191199
BeanRegistryAdapter adapter = new BeanRegistryAdapter(this.beanFactory, this.beanFactory, this.env, DefaultBeanRegistrar.class);
@@ -308,6 +316,14 @@ public void register(BeanRegistry registry, Environment env) {
308316
}
309317
}
310318

319+
private static class ScopeBeanRegistrar implements BeanRegistrar {
320+
321+
@Override
322+
public void register(BeanRegistry registry, Environment env) {
323+
registry.registerBean("foo", Foo.class, spec -> spec.scope("custom"));
324+
}
325+
}
326+
311327
private static class SupplierBeanRegistrar implements BeanRegistrar {
312328

313329
@Override

0 commit comments

Comments
 (0)