gpt4 book ai didi

java - Spring @Autowired 是按名称还是按类型注入(inject) bean?

转载 作者:IT老高 更新时间:2023-10-28 13:52:55 25 4
gpt4 key购买 nike

我正在阅读《初春》(威利出版社)的书。在第 2 章中有一个例子关于 Java 配置和 @Autowired。它提供了这个 @Configuration

@Configuration
public class Ch2BeanConfiguration {

@Bean
public AccountService accountService() {
AccountServiceImpl bean = new AccountServiceImpl();
return bean;
}

@Bean
public AccountDao accountDao() {
AccountDaoInMemoryImpl bean = new AccountDaoInMemoryImpl();
//depedencies of accountDao bean will be injected here...
return bean;
}

@Bean
public AccountDao accountDaoJdbc() {
AccountDaoJdbcImpl bean = new AccountDaoJdbcImpl();
return bean;
}
}

还有这个普通的 bean 类

public class AccountServiceImpl implements AccountService {

@Autowired
private AccountDao accountDao;

public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
...
}

当我运行代码时,它可以工作。但我预计会出现异常,因为我在配置中定义了 2 个具有相同类型的 bean。

我意识到它是这样工作的:

  • 如果 Spring 遇到多个具有相同类型的 bean,它会检查字段名称。
    • 如果它找到一个具有目标字段名称的 bean,它会将那个 bean 注入(inject)到该字段中。

这不是错的吗? Spring 对 Java 配置的处理是否存在错误?

最佳答案

documentation解释这个

For a fallback match, the bean name is considered a default qualifier value. Thus you can define the bean with an id "main" instead of the nested qualifier element, leading to the same matching result. However, although you can use this convention to refer to specific beans by name, @Autowired is fundamentally about type-driven injection with optional semantic qualifiers. This means that qualifier values, even with the bean name fallback, always have narrowing semantics within the set of type matches; they do not semantically express a reference to a unique bean id

所以,不,这不是错误,这是预期的行为。如果按类型 Autowiring 未找到单个匹配的 bean,则 bean id(名称)将用作后备。

关于java - Spring @Autowired 是按名称还是按类型注入(inject) bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30360589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com