Spring @Autowired 是按名称还是按类型注入 bean? [英] Does Spring @Autowired inject beans by name or by type?

查看:64
本文介绍了Spring @Autowired 是按名称还是按类型注入 bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am reading beginning spring (wiley press) book. In chapter 2 there is an example about Java configuration and @Autowired. It provides this @Configuration class

@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 类

and this regular bean class

public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

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

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

When I run the code, it works. But I expected an exception because I have defined 2 beans with the same type in the configuration.

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

I realized it works like this:

  • 如果 Spring 遇到多个相同类型的 bean,它会检查字段名称.
    • 如果找到具有目标字段名称的 bean,则将该 bean 注入该字段.

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

    Isn't this wrong? Is there a bug in Spring's handling of Java configuration?

    推荐答案

    文档 解释了这一点

    对于后备匹配,bean 名称被视为默认限定符 因此,您可以使用 id main"而不是嵌套的限定符元素,导致相同的匹配结果.不过,虽然你可以用这个约定来指代特定的bean 按名称,@Autowired 基本上是关于类型驱动的注入带有可选的语​​义限定符.这意味着限定符值,即使使用 bean 名称回退,也总是具有缩小语义在类型匹配集内;他们没有在语义上表达一个引用唯一的 bean id

    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

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

    So, no, it's not a bug, that is the intended behavior. The bean id (name) will be used as a fallback if a by-type autowiring doesn't find a single matching bean.

    这篇关于Spring @Autowired 是按名称还是按类型注入 bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆