我想知道是只有我一个人还是大多数 Spring 的 Java 配置有缺陷的例子?例如这里:
http://spring.io/blog/2008/03/27/spring-java-configuration-what-s-new-in-m3 http://spring.io/blog/2013/07/18/javaconfig-support -in-the-spring-tool-suite
注意他们是如何注入 bean 的?他们直接使用方法,例如:new OrderRepository(dataSource())
这里:
@Configuration
public class ApplicationConfig {
public @Bean OrderRepository orderRepository() {
return new OrderRepository(dataSource());
}
public @Bean DataSource dataSource() {
// instantiate and return an new DataSource ...
}
}
这让我开始思考——如果使用两次,它不会创建两个对象吗?有效绕过Spring的单例保证?他们为什么不注射豆子呢?因为依赖框架最初是为了工作而设计的。
让我们做一个快速测试。以这两个类为例 - TestParent 和 TestedChild。父母接受孩子:new TestParent(new TestedChild())
。我们将在一分钟内使它们成为单例豆。
public class TestedChild { }
public class TestParent {
private TestedChild child;
public TestParent(TestedChild child) {
this.child = child;
}
public TestedChild getChild() { return child; }
}
我想看看我们是否真的可以在上下文初始化期间创建两个不同的 TestedChild 实例。现在让我们配置我们的单例 bean:
@Configuration
public class TestInjectionConfig {
@Bean(name = "injected")
public TestParent injected(TestedChild bean) {
return new TestParent(bean);
}
@Bean(name = "direct")
public TestParent direct() {
return new TestParent(testedBean());
}
@Bean
public TestedChild testedBean() {
return new TestedChild();
}
}
我正在创建两个不同的 TestParent 对象,它们应该在创建时注入相同的 TestedChild 。
让我们测试一下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestInjectionConfig.class)
public class InjectionApplicationTest {
@Inject @Named("injected")
TestParent injected;
@Inject @Named("direct")
TestParent direct;
@Test
public void instancesShouldBeTheSame() {
Assert.assertSame(injected, direct);
}
}
我希望豆子是一样的,但这就是我在 Spring 3.2.6 上得到的:
junit.framework.AssertionFailedError: expected same:<pl.aie.TestParent@59e5a42c> was not:<pl.aie.TestParent@737d72cf>
回到问题。为什么示例在 Spring 配置类上使用直接方法调用?如果它们是这样被调用的,为什么用 @Bean 注释来注释它们?这是一种不好的做法,还是我的逻辑/代码在某处有缺陷?