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

由于按类型自动装配可能导致多个候选者,因此通常需要更好地控制选择过程。一种实现方法是使用 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 { ... }

	// ...
}

或者,从 6.2 版本开始,可以使用@Fallback 注解来标记除常规 Bean 之外的任何 Bean 以进行注入。如果只留下一个常规 Bean,它实际上也为主 Bean。

  • Java

  • Kotlin

@Configuration
public class MovieConfiguration {

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

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

	// ...
}
@Configuration
class MovieConfiguration {

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

	@Bean
	@Fallback
	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>