gpt4 book ai didi

spring - 在Spring中, 'autowire = Autowire.NO'有什么作用?

转载 作者:行者123 更新时间:2023-12-02 00:53:32 26 4
gpt4 key购买 nike

来自this Spring documentation我知道当我使用@Bean时,默认值已经相当于:

@Bean(autowire = Autowire.NO)

(Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.

我只是想了解这对我意味着什么。如果我的系统是 100% Java 配置并且没有 XML 配置,那么据我所知,当我使用 @Bean 时,“Autowire.no”不会产生任何影响。

编辑

“无影响”是指对该 bean 的其他 @Autowired 引用是 Autowiring 的(在其他 Java Config 类中)。我怀疑这是因为 Java Config 没有定义明确的“ref 元素”,所以这个(默认)设置没有效果。

示例:

第一个配置:

package a.b.c;

@Configuration
public class AlphaConfig {

@Bean(autowire = Autowire.NO)
public AlphaBeanType alphaBean() {
return new AlphaBeanType();
}
}

然后在第二个配置中:

package d.e.f;

import a.b.c.AlphaBeanType;

@Configuration
public class AnotherConfig {

@Autowire
private AlphaBeanType alphaBeanType;

@Bean
. . .
}

我看到的是“alphaBeanType”总是在第二个配置类中 Autowiring - 这似乎与文档冲突 - 因此我的问题。

结束编辑

当然,我无法从文档中完全看出!有谁确切知道吗?

最佳答案

设置Autowire.NO并不意味着该bean不能通过@Autowire注入(inject)到其他bean中。 @Autowire 默认按类型工作,也可以使用 @Qualifier 按名称工作。

因此,如果您的 bean 具有正确的类型或名称,它将被注入(inject)到其他 bean 中,这是正常的。

Autowire.NO 的意思是:

Don't inject the properties of THIS bean being declared with @Bean neither by type or by name. If the bean properties are not set in the @Bean method code, leave them unfilled.

这是一个说明其工作原理的代码示例,让我们定义两个 bean:

public class MyBeanTwo {

public MyBeanTwo() {
System.out.println(">>> MY Bean 2 created!");
}
}

public class MyBean {

private MyBeanTwo myBeanTwo;

public MyBean() {
System.out.println(">>>MyBean created !!");
}

public void setMyBeanTwo(MyBeanTwo myBeanTwo) {
System.out.println(">>> Injecting MyBeanTwo INTO MyBeanOne !!!");
this.myBeanTwo = myBeanTwo;
}
}

还有一些配置:

@Configuration
public class SimpleConfigOne {

@Bean
public MyBean createMyBean() {
return new MyBean();
}

@Bean
public MyBeanTwo createMyBeanTwo() {
return new MyBeanTwo();
}
}

使用此配置,该应用程序的启动会给出以下日志:

>>>MyBean created !!
>>> MY Bean 2 created!

这意味着每个 bean 的一个实例已创建,但 MyBean 并未注入(inject) MyBeanTwo,即使存在具有正确类型的 bean。

通过这样声明MyBean:

@Bean(autowire = Autowire.BY_TYPE)
public MyBean createMyBean() {
return new MyBean();
}

MyBeanOne 现在可以通过类型 Autowiring 来设置其属性。

启动日志变为:

>>>MyBean created !!
>>> MY Bean 2 created!
>>> Injecting MyBeanTwo INTO MyBeanOne !!!

这表明 MyBean 通过按类型注入(inject)按类型注入(inject)了 MyBeanTwo

Autowire.NO 为默认值的原因:

通常我们不想 Autowiring 使用@Bean创建的bean的属性。我们通常做的是通过代码显式设置属性以提高可读性,作为文档的形式并确保属性设置为正确的值。

关于spring - 在Spring中, 'autowire = Autowire.NO'有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21020187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com