|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
使用 @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>