@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 Config并且没有XML配置,那么从我可以看出,当我使用@Bean时,’Autowire.no’没有任何影响.
编辑
“没有影响”我的意思是对这个bean的其他@Autowired引用是自动装配的(在其他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’总是在第二个配置类中自动装配 – 这似乎与文档冲突 – 因此我的问题.
结束编辑
当然,我不能从文档中说出来!有人有确切消息么?
因此,如果您的bean具有正确的类型或名称,它将被注入其他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没有注入MyBeanTwo,即使是存在正确类型的bean也很难.
通过像这样声明MyBean:
@Bean(autowire = Autowire.BY_TYPE)
public MyBean createMyBean() {
return new MyBean();
}
MyBeanOne现在有资格通过类型自动装配设置它的属性.
启动日志变为:
>>>MyBean created !!
>>> MY Bean 2 created!
>>> Injecting MyBeanTwo INTO MyBeanOne !!!
这表明MyBean通过类型注入按类型注入了MyBeanTwo.
Autowire.NO是默认值的原因:
通常我们不想自动装配使用@Bean创建的bean的属性.我们通常做的是通过代码显式设置属性以提高可读性,作为文档的一种形式,并确保使用正确的值设置属性.
转载注明原文:在Spring,’autowire = Autowire.NO’做什么? - 乐贴网