Rop*_*Rop 13 spring dependency-injection spring-boot spring-java-config
浏览Spring Javaconfig参考文档 http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/beans.html 我发现了一些令人困惑的部分......
在"5.12.4使用@Configuration注释"部分中,它说:
"当@Beans彼此依赖时,表达该依赖关系就像让一个bean方法调用另一个一样简单:
@Configuration
public class AppConfig {
@Bean
public Foo foo() {
return new Foo(bar());
}
@Bean
public Bar bar() {
return new Bar();
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,foo bean通过构造函数注入接收对bar的引用."
好吧,如果一切都是无状态的,那可能并不重要,但如果您有上面的配置,然后在您的应用程序中执行:
@Autowired
private Foo foo;
@Autowired
private Bar bar;
Run Code Online (Sandbox Code Playgroud)
检查豆的散列码,事实证明,你的私有变量栏会指不同的实例的酒吧比一个通过使用富,这可能不是你所期望的,对不对?
我想说正常模式应该是:
@Configuration
public class AppConfig {
@Bean
public Bar bar() {
return new Bar();
}
@Autowired Bar bar;
@Bean
public Foo foo() {
return new Foo(bar);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当您在应用程序中自动装配两个bean时,您将只创建一个Bar实例.
我错过了什么,或者我是否正确文档在这里是片状的?
然后,再进一步,在"有关基于Java的配置如何在内部工作的更多信息"部分下, 看起来他们试图"澄清"此问题:
@Configuration
public class AppConfig {
@Bean
public ClientService clientService1() {
ClientServiceImpl clientService = new ClientServiceImpl();
clientService.setClientDao(clientDao());
return clientService;
}
@Bean
public ClientService clientService2() {
ClientServiceImpl clientService = new ClientServiceImpl();
clientService.setClientDao(clientDao());
return clientService;
}
@Bean
public ClientDao clientDao() {
return new ClientDaoImpl();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,不幸的是,这个配置甚至不会在运行时加载,因为有两个相同类型的bean,ClientService,没有区别属性,所以得到异常
org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type [.....] is defined:
expected single matching bean but found 2
Run Code Online (Sandbox Code Playgroud)
但即使我们稍微改变了这个例子,并给出前两个bean不同的类型,
@Bean
public ClientService1 clientService1() {...clientDao()...}
@Bean
public ClientService2 clientService2() {...clientDao()...}
@Bean
public ClientDao clientDao() {
return new ClientDaoImpl();
}
Run Code Online (Sandbox Code Playgroud)
这仍然是不正确的,因为 - 与文本声称的相反 - 当自动装配所有3个bean时,我们仍然会创建3个不同的ClientDaoImpl实例.
我是否完全错过了一些东西,或者说文档真的像我看来一样糟糕?
编辑:添加了一个演示,将演示我看到的问题:
一个bean ServiceA,以及两个bean ServiceB1,ServiceB2,构造函数注入ServiceA.
然后两个测试类Config01Test和Config02Test除配置外完全相同.第一次测试PASSES,第二次失败因为唯一性 - 断言.
| 归档时间: |
|
| 查看次数: |
7375 次 |
| 最近记录: |