這是回答上述評論,但由於意見已有限的格式化和大小,我會用一個答案來回答。
加載配置文件時
這取決於你通過加載多個配置的意思如何界定春豆的順序和壓倒一切的。如果你有一個spring上下文,並且有兩個帶@Configuration的類並且執行了組件掃描,那麼Spring將構建依賴樹,並且最後加載哪個上下文(bean)將定義該bean(因爲它覆蓋了第一個定義)。
如果你在父子關係中有多個Spring上下文,那麼這個子類就會看到父類bean,並且如果你使用child.getBean(type.class),它也會'覆蓋'父類。父母不能從孩子看到豆。
使用@Primary。如果你有一個Spring上下文(可以來自多個配置)定義了兩個相同類型的bean,你將不能使用context.getBean(type.class)或@AutoWired(沒有@Qualifier),因爲你有多個bean屬於同一類型。如果其中一個bean是@Primary,則可以更改此行爲。我儘量避免在自己的代碼中使用@Primary,但我可以看到它在Spring靴子自動配置系統中大量使用,所以我認爲它在框架設計方面有一些細微的用法。
這是一個小例子,請注意,如果直接加載配置類,則不需要具有@Configuration註釋。
public class ParentChildContext {
public static void main(String[] args) {
parentChildContext();
twoConfigurationsSameContext();
}
private static void twoConfigurationsSameContext() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(Parent.class, Child.class);
// if you have two beans of the same type in a context they can be loaded by name
Object childA = ctx.getBean("childA");
System.out.println("childA = " + childA);
Object parentA = ctx.getBean("parentA");
System.out.println("parentA = " + parentA);
// since both configurations define A, you can't do this
ctx.getBean(A.class);
}
private static void parentChildContext() {
ApplicationContext parentCtx = new AnnotationConfigApplicationContext(Parent.class);
A parentA = parentCtx.getBean(A.class);
System.out.println("parent = " + parentA);
AnnotationConfigApplicationContext childCtx = new AnnotationConfigApplicationContext();
childCtx.register(Child.class);
childCtx.setParent(parentCtx);
childCtx.refresh();
A childA = childCtx.getBean(A.class);
System.out.println("child = " + childA);
}
public static class Parent {
@Bean
//@Primary // if you enable @Primary parent bean will override child unless the context is hierarchical
public A parentA() {
return new A("parent");
}
}
public static class Child {
@Bean
public A childA() {
return new A("child");
}
}
public static class A {
private final String s;
public A(String s) {
this.s = s;
}
@Override
public String toString() {
return "A{s='" + s + "'}";
}
}
}
似乎是最合適的解決方案,我接受了答案,無論如何,知道爲什麼採用基本配置而不是客戶端特定配置,Spring會如何在加載配置文件時定義bean的排序和重寫? – simonC
如果您有兩種配置,您可以在兩種情況下加載它們,首先是父母,然後是孩子。孩子可以看到父母的豆子,但沒有其他方式。另外 –
忽視上面的評論。我會寫一個額外的答案,因爲在stackoverflow上的評論是非常蹩腳的! –