我正在读初春(威利出版社)书。在第二章中有一个例子
关于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配置时是否存在错误?

最佳答案

documentation对此进行了解释


  对于后备匹配,bean名称被视为默认限定符
  值。因此,您可以使用ID“ main”而不是ID定义bean。
  嵌套的限定符元素,导致相同的匹配结果。
  但是,尽管您可以使用此约定来引用特定的
  从名称上讲,@Autowired基本上是关于类型驱动的注入的
  带有可选的语​​义限定词。这意味着限定符值,
  即使bean名称回退,也总是具有狭窄的语义
  在类型匹配的集合内;他们没有在语义上表达
  引用唯一的bean ID


因此,不,这不是错误,而是预期的行为。如果按类型自动装配找不到单个匹配的bean,则将bean id(名称)用作备用。

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

10-11 22:32
查看更多