程式設計式 Bean 註冊

自 Spring Framework 7 起,透過 BeanRegistrar 介面提供了對程式設計式 Bean 註冊的一流支援,該介面可用於以靈活高效的方式程式設計式註冊 Bean。

這些 Bean 註冊器實現通常透過 @Configuration 類上的 @Import 註解匯入。

  • Java

  • Kotlin

@Configuration
@Import(MyBeanRegistrar.class)
class MyConfiguration {
}
@Configuration
@Import(MyBeanRegistrar::class)
class MyConfiguration {
}
您可以利用型別級別的條件註解(@Conditional,以及其他變體)來有條件地匯入相關的 Bean 註冊器。

Bean 註冊器實現使用 BeanRegistryEnvironment API 來以簡潔靈活的方式程式設計式註冊 Bean。例如,它允許透過 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!")));
		}
		registry.registerBean(MyRepository.class);
		registry.registerBean(RouterFunction.class, spec ->
				spec.supplier(context -> router(context.bean(MyRepository.class))));
	}

	RouterFunction<ServerResponse> router(MyRepository myRepository) {
		return RouterFunctions.route()
				// ...
				.build();
	}

}
class MyBeanRegistrar : BeanRegistrarDsl({
	registerBean<Foo>()
	registerBean(
		name = "bar",
		prototype = true,
		lazyInit = true,
		description = "Custom description") {
		Bar(bean<Foo>()) // Also possible with Bar(bean())
	}
	profile("baz") {
		registerBean { Baz("Hello World!") }
	}
	registerBean<MyRepository>()
	registerBean {
		myRouter(bean<MyRepository>()) // Also possible with myRouter(bean())
	}
})

fun myRouter(myRepository: MyRepository) = router {
	// ...
}
Bean 註冊器支援 預編譯最佳化,無論是在 JVM 上還是使用 GraalVM 本機映像,包括在使用例項提供者時。
© . This site is unofficial and not affiliated with VMware.