此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.6! |
编程 Bean 注册
从 Spring Framework 7 开始,对编程 bean 注册的一流支持是
通过BeanRegistrar
接口,该接口可以实现以编程方式在 Flexible 和
高效的方式。
这些 bean 注册商实现通常使用@Import
注解
上@Configuration
类。
-
Java
-
Kotlin
@Configuration
@Import(MyBeanRegistrar.class)
class MyConfiguration {
}
@Configuration
@Import(MyBeanRegistrar::class)
class MyConfiguration {
}
您可以利用类型级条件注释 (@Conditional ,
还有其他变体)来有条件地导入相关的 bean registrars。 |
bean registrar 实现使用BeanRegistry
和Environment
以简洁的方式以编程方式注册 bean 的 API
和灵活的方式。例如,它允许通过if
表达式、for
循环等。
-
Java
-
Kotlin
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 注册商受 Ahead of Time Optimization 支持, 在 JVM 上或使用 GraalVM 原生映像,包括使用实例供应商时。 |