Spring ApplicationContext with multiple XML Files

2019-02-19 13:11发布

问题:

I need to create a ApplicationContext with the "main" applicationContext-a.xml from the current Maven build. The other one wires classes from another maven build and is preset in the jar included by a Maven Dependency.

Here the idea:

ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {
                "classpath*:applicationContext-*.xml"});

This should load applicationContext-a.xml from the Classpath because it's in the same Project. This works.

Then applicationContext-b.xml should be loaded from the dependency-jar. This doesn't work.

Note that

"classpath*:applicationContext-*.xml"

Only matches the XMLs inside the direct classpath, nothing inside the jar.

What i found out:

ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {
                "classpath*:applicationContext-*.xml", "classpath*:applicationContext-b.xml"});

This works, but only if i explicitly can tell the filename of the xml inside the jar: applicationContext-b.xml

I also need this to work for Integration Tests:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"**/applicationContext*.xml"})
public class TestClass { ... }

The best idea might be a custom loader? There have to be a way to get this Pattern work...

There was a solution some time ago, which works the other way round: It only gets the applicationContext.xml from the jar. If there's anotherone inside the classpath it only matches on this file.

回答1:

The classpath*: I think has a limitation doesn't work for files under the root folder. Try moving the files under a folder - something like spring/application-a.xml and spring/application-b.xml. Then you can have a path classpath*:/spring/application-*.xml.