跳到主要内容
版本:7.0.3

使用 @Primary@Fallback 对基于注释的自动连接进行微调

Hunyuan 7b 中英对照 Fine-tuning Annotation-based Autowiring with @Primary or @Fallback Fine-tuning Annotation-based Autowiring with @Primary or @Fallback

由于类型自动配置可能会导致多个候选Bean,因此通常需要对选择过程有更多的控制。实现这一目标的一种方法是使用Spring的@Primary注解。@Primary表示当有多个Bean可以作为单个值依赖的自动配置候选时,应优先选择某个特定的Bean。如果在候选Bean中恰好存在一个唯一的@Primary Bean,那么它就会成为自动配置的值。

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

@Configuration
public class MovieConfiguration {

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

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

// ...
}

或者,从版本6.2开始,有一个@Fallback注解,用于标记除了常规bean之外的其他需要注入的bean。如果只剩下一个常规bean,那么它实际上也会被视为主要bean(primary)。

@Configuration
public class MovieConfiguration {

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

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

// ...
}

使用上述配置的两种变体,以下的 MovieRecommender 都会自动与 firstMovieCatalog 连接(即实现自动配置):

public class MovieRecommender {

@Autowired
private 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>