对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
Bean 定义 DSL
Spring Framework 支持使用 lambda 以功能方式注册 bean
作为 XML 或 Java 配置 (@Configuration
和@Bean
).简而言之
它允许您使用充当FactoryBean
.
这种机制非常有效,因为它不需要任何反射或 CGLIB 代理。
例如,在 Java 中,您可以编写以下内容:
class Foo {}
class Bar {
private final Foo foo;
public Bar(Foo foo) {
this.foo = foo;
}
}
GenericApplicationContext context = new GenericApplicationContext();
context.registerBean(Foo.class);
context.registerBean(Bar.class, () -> new Bar(context.getBean(Foo.class)));
在 Kotlin 中,使用具体化的类型参数和GenericApplicationContext
Kotlin 扩展、
您可以改为编写以下内容:
class Foo
class Bar(private val foo: Foo)
val context = GenericApplicationContext().apply {
registerBean<Foo>()
registerBean { Bar(it.getBean()) }
}
当类Bar
有一个构造函数,你甚至可以只指定 bean 类
构造函数参数将按类型自动装配:
val context = GenericApplicationContext().apply {
registerBean<Foo>()
registerBean<Bar>()
}
为了实现更具声明性的方法和更简洁的语法, Spring Framework 提供了
一个 Kotlin bean 定义 DSL 它声明了一个ApplicationContextInitializer
通过一个干净的声明式 API,
它允许您处理配置文件和Environment
用于定制
如何注册 bean。
在以下示例中,请注意:
-
类型推断通常允许避免为 bean 引用指定类型,例如
ref("bazBean")
-
可以使用 Kotlin 顶级函数通过可调用引用(如
bean(::myRouter)
在此示例中 -
指定
bean<Bar>()
或bean(::myRouter)
,参数按类型自动装配 -
这
FooBar
仅当foobar
配置文件处于活动状态
class Foo
class Bar(private val foo: Foo)
class Baz(var message: String = "")
class FooBar(private val baz: Baz)
val myBeans = beans {
bean<Foo>()
bean<Bar>()
bean("bazBean") {
Baz().apply {
message = "Hello world"
}
}
profile("foobar") {
bean { FooBar(ref("bazBean")) }
}
bean(::myRouter)
}
fun myRouter(foo: Foo, bar: Bar, baz: Baz) = router {
// ...
}
此 DSL 是编程的,这意味着它允许自定义 bean 的注册逻辑
通过if 表达式、for loop 或任何其他 Kotlin 结构。 |
然后,您可以使用此beans()
在应用程序上下文中注册 bean 的函数,
如下例所示:
val context = GenericApplicationContext().apply {
myBeans.initialize(this)
refresh()
}
Spring Boot 基于 JavaConfig,尚未为函数式 bean 定义提供特定支持。
但是您可以通过 Spring Boot 的ApplicationContextInitializer 支持。
有关更多详细信息和最新信息,请参阅此 Stack Overflow 答案。另请参阅在 Spring Fu 培养箱中开发的实验性 Kofu DSL。 |