[英]How will Spring handle two XML config files with the same name?
I have a project A which dependent on B.jar and C.jar. 我有一个项目B,它依赖于B.jar和C.jar。 They both have a resource file named
spring-datasource.xml
in classpath. 它们在类路径中都有一个名为
spring-datasource.xml
的资源文件。 When project A import spring-datasouce.xml
, which one will be chosed? 当项目A导入
spring-datasouce.xml
,将选择哪个? How does A make the decision? A如何做出决定?
If these two files contain different bean definitions then it will simply create all the bean definitions in both of these files. 如果这两个文件包含不同的bean定义,那么它将仅在这两个文件中创建所有bean定义。 The fact that the files have the same name is irrelevant.
文件具有相同名称的事实无关紧要。
If the two files define beans with the same name then Spring will override the earlier definition with the later definition. 如果两个文件用相同的名称定义bean,那么Spring将用较新的定义覆盖较早的定义。 For example: if
B.jar::spring-datasource.xml
and C.jar::spring-datasource.xml
both contains a bean named dataSource
then ... 例如:如果
B.jar::spring-datasource.xml
和C.jar::spring-datasource.xml
都包含一个名为dataSource
的bean,则...
B.jar::spring-datasource.xml
first it will create the dataSource
bean as per the definition in that file and then when it encounters C.jar::spring-datasource.xml
it will override the dataSource
bean with the definition in C.jar::spring-datasource.xml
bean.3 B.jar::spring-datasource.xml
首先它会创建dataSource
豆按照该文件中的定义,然后当它遇到C.jar::spring-datasource.xml
它将覆盖dataSource
豆与C.jar::spring-datasource.xml
bean.3中的定义 C.jar::spring-datasource.xml
first then the reverse will happen. C.jar::spring-datasource.xml
那么将发生相反的情况。 This term: "encounters first" refers to the way in which Spring discovers XML configuration files ie the ordering of the files as they are loaded into the Spring context. 这个术语:“首先遇到”是指Spring发现XML配置文件的方式,即文件在加载到Spring上下文中时的顺序。 Typically, this will be controlled by the order of
B.jar
and C.jar
in your runtime classpath. 通常,这将由运行时类路径中
B.jar
和C.jar
的顺序控制。
If you are concerned about this ie if you need to be certain about the order in which your beans are declared then either: 如果您对此有所担心,即如果需要确定声明bean的顺序,则可以:
B.jar
and C.jar
in your classpath delivers these XML files to the Spring context in your preferred order B.jar
和C.jar
的顺序以您喜欢的顺序将这些XML文件传递到Spring上下文中 This isn't really recommended; 确实不建议这样做; it's brittle and error prone.
它很脆弱且容易出错。
FWIW using Java config with the @Primary
annotation or using Spring Profiles to control what Spring config is loaded would both offer more control over this situation. FWIW使用带有
@Primary
批注的Java配置或使用Spring Profiles来控制Spring配置的加载,都将提供对这种情况的更多控制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.