【发布时间】:2015-08-02 08:16:52
【问题描述】:
我正在阅读《初春》(威利出版社)的书。在第 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 注入到该字段中。
这不是错的吗? Spring 对 Java 配置的处理是否存在错误?
【问题讨论】:
-
我完全理解你为什么对此感到困惑——因为it's bad design, IMO。
标签: java spring configuration code-injection autowired