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

由于按类型自动装配可能导致多个候选,因此通常需要对选择过程进行更多控制。实现此目的的一种方法是使用 Spring 的 @Primary 注释。@Primary 表示当多个 bean 是自动装配到单值依赖项的候选时,应优先考虑特定 bean。如果候选者中只有一个主要 bean,则它将成为自动装配的值。

考虑以下将 firstMovieCatalog 定义为主要 MovieCatalog 的配置

  • Java

  • Kotlin

@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 会自动装配到 firstMovieCatalog

  • Java

  • Kotlin

public class MovieRecommender {

	@Autowired
	private MovieCatalog movieCatalog;

	// ...
}
class MovieRecommender {

	@Autowired
	private lateinit var movieCatalog: MovieCatalog

	// ...
}

相应的 bean 定义如下

<?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>