此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

程序化 Bean 注册

从 Spring Framework 7 开始,对编程 Bean 注册的一流支持是 通过BeanRegistrar接口,可以实现以编程方式在灵活的 有效的方式。spring-doc.cadn.net.cn

这些 bean 注册器实现通常与@Import注解 上@Configuration类。spring-doc.cadn.net.cn

@Configuration
@Import(MyBeanRegistrar.class)
class MyConfiguration {
}
@Configuration
@Import(MyBeanRegistrar::class)
class MyConfiguration {
}
您可以利用类型级条件注释 (@Conditional, 以及其他变体)有条件地导入相关的 bean 注册商。

bean registrar 实现使用BeanRegistryEnvironment以编程方式以简洁的方式注册 Bean 的 API 和灵活的方式。例如,它允许通过if表达式,一个for循环等。spring-doc.cadn.net.cn

class MyBeanRegistrar implements BeanRegistrar {

    @Override
    public void register(BeanRegistry registry, Environment env) {
        registry.registerBean("foo", Foo.class);
        registry.registerBean("bar", Bar.class, spec -> spec
                .prototype()
                .lazyInit()
                .description("Custom description")
                .supplier(context -> new Bar(context.bean(Foo.class))));
        if (env.matchesProfiles("baz")) {
            registry.registerBean(Baz.class, spec -> spec
                    .supplier(context -> new Baz("Hello World!")));
        }
    }
}
class MyBeanRegistrar : BeanRegistrarDsl({
    registerBean<Foo>()
    registerBean(
        name = "bar",
        prototype = true,
        lazyInit = true,
        description = "Custom description") {
            Bar(bean<Foo>())
    }
    profile("baz") {
        registerBean { Baz("Hello World!") }
    }
})
Bean 注册商通过提前优化, 无论是在 JVM 上还是使用 GraalVM 本机映像,包括使用实例提供商时。