对于最新的稳定版本,请使用 Spring Framework 6.2.4spring-doc.cadn.net.cn

基本概念:@Bean@Configuration

Spring 的 Java 配置支持中的核心工件是@Configuration-annotated 类和@Bean-annotated 方法。spring-doc.cadn.net.cn

@Beanannotation 用于指示方法 instantiates、configure 和 初始化一个要由 Spring IoC 容器管理的新对象。对于熟悉的人 与 Spring 的<beans/>XML 配置、@Beanannotation 的作用与 这<bean/>元素。您可以使用@Bean-annotated 方法与任何 Spring@Component.但是,它们最常与@Configuration豆。spring-doc.cadn.net.cn

使用@Configuration表示其主要用途是作为 bean 定义的来源。此外@Configuration类 let inter-bean dependencies 通过调用其他@Bean方法。 尽可能简单@Configuration类读取如下:spring-doc.cadn.net.cn

@Configuration
public class AppConfig {

	@Bean
	public MyServiceImpl myService() {
		return new MyServiceImpl();
	}
}
@Configuration
class AppConfig {

	@Bean
	fun myService(): MyServiceImpl {
		return MyServiceImpl()
	}
}

前面的AppConfigclass 等价于下面的 Spring<beans/>XML:spring-doc.cadn.net.cn

<beans>
	<bean id="myService" class="com.acme.services.MyServiceImpl"/>
</beans>
Full @Configuration vs “lite” @Bean模式?

什么时候@Bean方法在未使用@Configuration,它们被称为以 “lite” 模式处理。Bean 方法 在@Component甚至在普通的旧类中都被认为是 “lite”, 具有不同的 Primary 用途,并且@Bean方法 在那里是一种奖励。例如,服务组件可能会公开管理视图 通过额外的@Bean方法。 在这种情况下,@Beanmethods 是一种通用的工厂方法机制。spring-doc.cadn.net.cn

与完整@Configuration建兴@Bean方法不能声明 bean 间的依赖关系。 相反,它们对其包含组件的内部 state 进行作,并且可以选择对 他们可以声明的参数。这样的@Beanmethod 不应调用其他@Bean方法。每个这样的方法实际上都只是一个特定 bean 引用,而不需要任何特殊的运行时语义。这里的积极副作用是 在运行时不必应用 CGLIB 子类化,因此 类 design 的术语(即,包含类可以是final等等)。spring-doc.cadn.net.cn

在常见场景中,@Bean方法将在@Configuration类 确保始终使用 “full” 模式,因此跨方法引用 重定向到容器的生命周期管理。这可以防止相同的@Bean方法,这有助于 减少在 “Lite” 模式下运行时难以追踪的细微错误。spring-doc.cadn.net.cn

@Bean@Configuration以下部分将深入讨论 Comments。 但是,首先,我们介绍了使用 基于 Java 的配置。spring-doc.cadn.net.cn