這發生在我將@Configuration
帶註釋的類進行子類化時,並將其饋送到AnnotationConfigApplicationContext
爲什麼這個基於Java的Spring配置創建兩個單例bean的實例?
下面的這些類將總結該場景。這裏是full source
public class Bar {}
public class Foo {
private Bar bar;
public Foo(Bar bar) { this.bar = bar; }
@Override public String toString() {
return super.toString() + "(" + bar + ")";
}
}
@Configuration
public class BaseAppConfig {
@Bean public Foo foo() { return new Foo(bar()); }
@Bean public Bar bar() { return new Bar(); }
}
/** Omitting @Configuration here */
public class AppConfig extends BaseAppConfig {
@Bean @Override public Bar bar() { return new Bar(); }
}
public class App {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx = new
AnnotationConfigApplicationContext(AppConfig.class)) {
System.out.println(ctx.getBean(Foo.class).toString());
System.out.println(ctx.getBean(Bar.class).toString());
}
}
}
這個打印兩種Bar
情況下,我希望看到相同的情況下兩次:
[email protected]([email protected])
[email protected]
指着我**模式**是真正的問題的答案。這解釋了一切。我在[@Bean文檔](http://docs.spring.io/spring/docs/4.1.1.RELEASE/javadoc-api/org/springframework/context/annotation/Bean.html)上找到了規範, – 2014-10-30 07:38:03