Monday, April 26, 2010

wildcards in spring application context loading

Spring supports wildcards for loading its configuration file.

classpath:*Context.xml

Or load configuration files in any sub-folders in the classpath

classpath:**/*Context.xml

If you have multiple resource repositories (directories, databases, online resources, whatever) on your classpath containing files that match your wildcard pattern, Spring will only look for matching resources in one of these locations. The snippet below can load configurations from multiple repositories

classpath*:**/*Context.xml

This article is originally from here

 



Note: "classpath*:" when combined with Ant-style patterns will only work reliably with at least one root directory before the pattern starts, unless the actual target files reside in the file system. This means that a pattern like "classpath*:*.xml" will not retrieve files from the root of jar files but rather only from the root of expanded directories. This originates from a limitation in the JDK's ClassLoader.getResources() method which only returns file system locations for a passed-in empty string (indicating potential roots to search).



Let’s say we have two project, app and app1. App1 depends on app. App has one spring context file app-context.xml and App1 has app1-context.xml. The bean defined in app1-context.xml need reference from app-context.xml. If the app-context.xml is on the root of the app jar file, “classpath*:*-context.xml” can not load it. It will give out the error “bean not defined” for the beans which are defined in app-context.xml. We need move the context file into some sub directory inside the jar, let’s say it is “META-INF”, then “classpath*:META-INF/*-context.xml”" can load the app-context.xml now.

No comments:

Post a Comment