|
此版本仍在开发中,尚未稳定。如需最新的稳定版本,请使用 Spring Framework 7.0.6! |
使用 @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,则它实际上也具有首要性:
-
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>