此版本仍在开发中,尚未稳定。如需最新的稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

程序化Bean注册

自Spring Framework 7起,通过BeanRegistration 接口提供了一流的程序化bean注册支持,可以实现该接口以灵活且高效的方式进行程序化的bean注册。spring-doc.cadn.net.cn

这些bean注册器实现通常是通过在配置类上使用@Import注解导入的。spring-doc.cadn.net.cn

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

Bean注册器实现使用BeanRegistryEnvironment API以简洁且灵活的方式编程式注册bean。例如,它允许通过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!")));
		}
		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原生镜像一起使用,包括当使用实例提供商时。