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

使用 @Primary 对基于注解的自动装配进行微调

由于按类型自动装配可能会导致多个候选 Bean,因此通常需要对选择过程进行更精细的控制。实现这一目标的方法之一是使用 Spring 的 @Primary 注解。@Primary 表示当多个 Bean 都符合单值依赖的自动装配条件时,应优先选择该特定的 Bean。如果在所有候选 Bean 中恰好存在一个主 Bean(primary bean),那么它就会被作为自动装配的值。spring-doc.cadn.net.cn

考虑以下配置,它将 firstMovieCatalog 定义为首选的 MovieCatalogspring-doc.cadn.net.cn

@Configuration
public class MovieConfiguration {

	@Bean
	@Primary
	public MovieCatalog firstMovieCatalog() { ... }

	@Bean
	public MovieCatalog secondMovieCatalog() { ... }

	// ...
}
@Configuration
class MovieConfiguration {

	@Bean
	@Primary
	fun firstMovieCatalog(): MovieCatalog { ... }

	@Bean
	fun secondMovieCatalog(): MovieCatalog { ... }

	// ...
}

通过上述配置,以下 MovieRecommender 将被自动装配为使用 firstMovieCatalogspring-doc.cadn.net.cn

public class MovieRecommender {

	@Autowired
	private MovieCatalog movieCatalog;

	// ...
}
class MovieRecommender {

	@Autowired
	private lateinit var movieCatalog: MovieCatalog

	// ...
}

对应的 Bean 定义如下:spring-doc.cadn.net.cn

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		https://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config/>

	<bean class="example.SimpleMovieCatalog" primary="true">
		<!-- inject any dependencies required by this bean -->
	</bean>

	<bean class="example.SimpleMovieCatalog">
		<!-- inject any dependencies required by this bean -->
	</bean>

	<bean id="movieRecommender" class="example.MovieRecommender"/>

</beans>