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

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

问题描述

我正在读初春(wiley press)的书。在第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类

public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

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

代码,它工作。但我期待一个异常,因为我在配置中定义了两个相同类型的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配置时有没有bug?

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

    推荐答案

    文档解释此


    对于后备匹配, bean名称被认为是默认限定符
    value。
    因此,您可以使用idmain而不是
    定义bean ,导致相同的匹配结果。
    然而,尽管你可以使用这个约定来按名称引用特定的
    bean,但是 @Autowired 基本上是关于类型驱动的注入
    具有可选的语​​义限定符
    。这意味着限定符值
    (即使使用bean名称fallback)在类型匹配集合中始终具有缩小的语义
    ;它们不会语义地表达对唯一的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(name)将用作后备。

    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天全站免登陆