使用 @Primary 或 @Fallback 对基于注释的自动连接进行微调
@Primary or @Fallback
由于类型自动配置可能会导致多个候选Bean,因此通常需要对选择过程有更多的控制。实现这一目标的一种方法是使用Spring的@Primary注解。@Primary表示当有多个Bean可以作为单个值依赖的自动配置候选时,应优先选择某个特定的Bean。如果在候选Bean中恰好存在一个唯一的@Primary 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(primary)。
- 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>