简体   繁体   English

@Bean (autowire = Autowire.BY_NAME)

[英]@Bean (autowire = Autowire.BY_NAME)

What is the purpose of setting the autowire property of @Bean to *Autowire.BY_NAME*@Bean的 autowire 属性设置为*Autowire.BY_NAME*的目的是什么

Looking at the JavDocs, I dont really know when I would use this, or why it would be set to *Autowire.BY_NAME*查看 JavaDocs,我真的不知道什么时候会使用它,或者为什么它会被设置为*Autowire.BY_NAME*

/**
 * Are dependencies to be injected via autowiring?
 */
Autowire autowire() default Autowire.NO;

I have an existing prototype bean that is created with我有一个现有的原型 bean,它是用

@Bean (autowire = Autowire.BY_NAME)

But I dont understand why.但我不明白为什么。 The comments only state:评论仅说明:

Note: We have to explicitly set Autowire.BY_NAME in the bean definitions to be able to use @Autowired in other spring config classes注意:我们必须在 bean 定义中显式设置 Autowire.BY_NAME 才能在其他 spring 配置类中使用 @Autowired

Does this mean we have to set a bean to @Bean (autowire = Autowire.BY_NAME) in order to be able to use the Bean with @Autowired and it will be autowired by name from the @Bean?这是否意味着我们必须将 bean 设置为 @Bean (autowire = Autowire.BY_NAME) 以便能够将 Bean 与 @Autowired 一起使用,并且它将通过 @Bean 的名称自动装配?

@Bean(autowire=Autowire.BY_NAME) is the equivalent of this xml configuration: @Bean(autowire=Autowire.BY_NAME)相当于这个 xml 配置:

<bean class="Person" id="person" autowire="byName"></bean>

which indicates whether the bean created using the above Person class, needs to have its fields autowired in "by name" - if the test bean above has a field say address , Spring will look for a bean with name address to inject as a dependency(not by type Address ).这表明使用上述Person类创建的 bean 是否需要在“按名称”中自动装配其字段 - 如果上面的测试 bean 有一个字段 say address ,Spring 将寻找具有名称address的 bean 作为依赖项注入(不是按类型Address )。

This is typically used if it is possible that there are more than 1 instances of a particular type, then you would select the specific instance using a name - again consider the example above if there were to be two address beans with names addressHome , addressWork and if Person class had a field with name addressHome and its set to Autowire.BY_NAME , the bean with name addressHome will be set to the field.如果特定类型的实例可能超过 1 个,则通常使用此方法,然后您将使用名称选择特定实例 - 再次考虑上面的示例,如果有两个地址 bean,名称为addressHomeaddressWork和如果Person类有一个名为addressHome的字段并将其设置为Autowire.BY_NAME ,则名为addressHome的 bean 将设置为该字段。 Had it been Autowire.BY_TYPE it would have failed as there are two instances of address of the same type Address如果是Autowire.BY_TYPE它会失败,因为有两个相同类型的Address实例Address

As @Bean (autowire = Autowire.BY_NAME) is deprecated.

No syntactical alternative, Autowire by Name is understood.没有语法替代方案,可以理解按名称自动装配。 You just have to provide same name as @Bean method name or @Component name.您只需要提供与@Bean 方法名称或@Component 名称相同的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM