简体   繁体   中英

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. They both have a resource file named spring-datasource.xml in classpath. When project A import spring-datasouce.xml , which one will be chosed? How does A make the decision?

If these two files contain different bean definitions then it will simply create all the bean definitions in both of these files. 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. For example: if B.jar::spring-datasource.xml and C.jar::spring-datasource.xml both contains a bean named dataSource then ...

  • If Spring encounters 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
  • If Spring encounters C.jar::spring-datasource.xml first then the reverse will happen.

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. Typically, this will be controlled by the order of B.jar and C.jar in your runtime classpath.

If you are concerned about this ie if you need to be certain about the order in which your beans are declared then either:

  • Do not have multiple definitions of the same bean name
  • Ensure that the order of B.jar and C.jar in your classpath delivers these XML files to the Spring context in your preferred order

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM