gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:19:29 26 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配置是否有bug?

最佳答案

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/38999155/

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