Bean 定义 DSL

Spring Framework 支持使用 lambda 以函数式方式注册 bean,作为 XML 或 Java 配置(@Configuration@Bean)的替代方案。简而言之,它允许你使用充当 FactoryBean 的 lambda 来注册 bean。这种机制非常高效,因为它不需要任何反射或 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。它通过简洁的声明式 API 声明了一个 ApplicationContextInitializer,让你能够处理配置文件和 Environment,从而自定义 bean 的注册方式。

在以下示例中请注意:

  • 类型推断通常允许避免为 ref("bazBean") 这样的 bean 引用指定类型

  • 可以使用 Kotlin 顶级函数通过可调用引用声明 bean,例如本例中的 bean(::myRouter)

  • 当指定 bean<Bar>()bean(::myRouter) 时,参数按类型自动装配

  • FooBar bean 仅在 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 是程序化的,这意味着它允许通过 if 表达式、for 循环或任何其他 Kotlin 构造函数进行 bean 的自定义注册逻辑。

然后,你可以使用这个 beans() 函数在应用程序上下文中注册 bean,如下例所示:

val context = GenericApplicationContext().apply {
	myBeans.initialize(this)
	refresh()
}

Spring Boot 基于 JavaConfig,并且 尚不支持函数式 bean 定义,但你可以通过 Spring Boot 的 ApplicationContextInitializer 支持实验性地使用函数式 bean 定义。有关更多详细信息和最新信息,请参阅 此 Stack Overflow 回答。另请参阅在 Spring Fu 孵化器 中开发的实验性 Kofu DSL。