跳到主要内容

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

ChatGPT-4o 中英对照 Fine-tuning Annotation-based Autowiring with @Primary or @Fallback Fine-tuning Annotation-based Autowiring with @Primary or @Fallback

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

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

@Configuration
public class MovieConfiguration {

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

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

// ...
}
java

或者,从 6.2 版本开始,有一个 @Fallback 注解用于标记除常规 bean 之外的任何其他 bean 以进行注入。如果只剩下一个常规 bean,它实际上也是主要的:

@Configuration
public class MovieConfiguration {

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

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

// ...
}
java

在上述配置的两种变体中,以下 MovieRecommender 被自动装配为 firstMovieCatalog

public class MovieRecommender {

@Autowired
private MovieCatalog movieCatalog;

// ...
}
java

相应的 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>
xml