Neglected classes in Spring – Part I
This blog post will be the starting point of a series of posts regarding often neglected classes in Spring. There are two main reasons for me to write this series. First, I really would like to unveil a set of classes that deserve some deeper attention as they make developer’s life a lot easier inside Spring, especially as they constantly stand in the shadows of BeanFactory, ApplicationContext and so on.
The second aspect is that I very often face the situation that whenever one mentions Spring the immediate reaction is: “Oh year, all this container-XML-thingamajiggy!”. What’s often being missed is that most (if not entirely all) of Spring is usable as library and thus even available if Spring is not the basis of your application. As this this results in the ability to seemlessly integrate Spring even into existing legacy code this can be a cruicial argument whether to migrate towards a particular technology. But enough of the reasoning, let’s dive in what to explore…
I’d like to start the series with a an interface that the common Spring developer uses a lot as it is heavily used inside Spring itself: ResourcePatternResolver. The interface extends ResourceLoader and adds the ability to lookup resources by patterns. The most used implementation of this interface is PathMatchingResourcePatternResolver. It understands the basic file: protocol as well as the really powerful classpath*: protocol. As the name suggests it allows scanning the classpath for resources. E.g. classpath*:foo/bar.xml collects all the bar.xml files inside a package/folder foo. The implementation also supports wildcards inside the path to the actual resource. So something like this is possible
ResourcePatternResolver resolver =
new PathMatchingResourcePatternResolver();
for (Resource resource : resolver.getResources(
"classpath*:META-INF/**/*.xml")) {
// do something usefull with the resource
}
Having said that there are some things to consider:
- … the order of the resources is pretty much undetermined as it uses the underlying classloader
- … you have to provide at least one fixed folder before the first wildcard as the pattern is resolved in two steps. The first step is to retrieve all resources up to the first wildcard and
ClassLoader.getResources()method only returns file system locations for empty strings. Thusclasspath*:*.xmlwill only return resources from expanded locations. (Consult the Javadocs ofPathMatchingResourcePatternResolverfor details.)
In general this is a handy tool to access files from the classpath or the filesystem from within an application, no matter if it’s configuration files or real data files.



Nice article!
I’m frequently using the ClassPathResource class (http://static.springsource.org/spring/docs/2.0.8/api/org/springframework/core/io/ClassPathResource.html) to load a defined “Resource”.