【Spring Boot `@Autowired` Annotation】

在Spring Boot中,@Autowired注解用于自动装配bean。默认情况下,它按照类型进行装配。当存在多个相同类型的bean时,就会出现以下错误:

***************************
APPLICATION FAILED TO START
***************************

Description:
Field <fieldName> in <ClassName> required a single bean, but <number> were found:
- BeanA: defined in file [<path/to/BeanA.class>]
- BeanB: defined in file [<path/to/BeanB.class>]

这种情况下,Spring无法明确选择哪个bean进行注入,因为存在多个匹配项。

解决这个问题有几种方式:

1. 使用@Qualifier注解

结合@Qualifier注解,指定要注入的bean名称。这样可以明确告诉Spring应该选择哪个bean。

示例:

@Component
public class YourClass {
    @Autowired
    @Qualifier("beanA") // 使用指定的bean名称
    private YourInterface yourBean;
}
2. 使用@Primary注解

在作为默认首选的bean上使用@Primary注解。这个bean会成为首选项被注入到需要的地方。

示例:

@Component
@Primary
public class PrimaryBean implements YourInterface {
    // Implementation
}
3. 手动注入(较少推荐)

手动注入可以避免@Autowired的自动装配。通过@Resource或者@Inject来手动指定要注入的bean。

示例:

@Component
public class YourClass {
    @Resource(name = "beanA") // 使用指定的bean名称
    private YourInterface yourBean;
}