Make scope fully configurable

Closes gh-36171
This commit is contained in:
Juergen Hoeller
2026-01-18 15:55:36 +01:00
parent 2d2809f45c
commit 7aa862f5ec
3 changed files with 29 additions and 0 deletions
@@ -207,6 +207,13 @@ public interface BeanRegistry {
*/
Spec<T> prototype();
/**
* Configure this bean with a custom scope.
* @since 7.0.4
* @see BeanDefinition#setScope(String)
*/
Spec<T> scope(String scope);
/**
* Set the supplier to construct a bean instance.
* @see AbstractBeanDefinition#setInstanceSupplier(Supplier)
@@ -279,6 +279,12 @@ public class BeanRegistryAdapter implements BeanRegistry {
return this;
}
@Override
public Spec<T> scope(String scope) {
this.beanDefinition.setScope(scope);
return this;
}
@Override
public Spec<T> supplier(Function<SupplierContext, T> supplier) {
this.beanDefinition.setInstanceSupplier(() ->
@@ -186,6 +186,14 @@ public class BeanRegistryAdapterTests {
assertThat(beanDefinition.getScope()).isEqualTo(AbstractBeanDefinition.SCOPE_PROTOTYPE);
}
@Test
void customScope() {
BeanRegistryAdapter adapter = new BeanRegistryAdapter(this.beanFactory, this.beanFactory, this.env, ScopeBeanRegistrar.class);
new ScopeBeanRegistrar().register(adapter, env);
BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition("foo");
assertThat(beanDefinition.getScope()).isEqualTo("custom");
}
@Test
void defaultSupplier() {
BeanRegistryAdapter adapter = new BeanRegistryAdapter(this.beanFactory, this.beanFactory, this.env, DefaultBeanRegistrar.class);
@@ -308,6 +316,14 @@ public class BeanRegistryAdapterTests {
}
}
private static class ScopeBeanRegistrar implements BeanRegistrar {
@Override
public void register(BeanRegistry registry, Environment env) {
registry.registerBean("foo", Foo.class, spec -> spec.scope("custom"));
}
}
private static class SupplierBeanRegistrar implements BeanRegistrar {
@Override