Tuesday, April 13, 2010

Difference between Classpath:* & Classpath*: in Spring

The difference between these two is the way the resources are found when a regular expression is given for match.

classpath*: -> This special prefix specifies that all classpath resources that match the given name must be obtained
(internally, this essentially happens via a ClassLoader.getResources(...) call), and then merged to form the final application context definition.

Ex classpath*:app*.xml && classpath:app*.xml is

With spring xmls, app1.xml and app2.xml and beans in app2.xml referring to app1.xml

- classpath:app*.xml will give errors if app1.xml and app2.xml are in two different classpath folders(It tries to find a matching app1 or app2 in classpath , and when
found doesnt continue to search further with other classpath locations.)

- classpath*:app*.xml will never give errors(searches for all classpath folders)

classpath* will search all classpath folder whereas classpath: will concentrate on one resource.

This also works for location attribute of PropertyPlaceHolderConfig

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath*:jdbc.properties"></property>

But important thing to be noted here is that property name is locations and not location.

One more difference with classpath*:config.xml and classpath:*config.xml

is that

classpath:*config.xml - if file(matching *config) isnt present it shows error in console

classpath*:*config.xml just ignores teh error if no file is present in the classpath.

classpath*: basically refers to a list of resources and a list can be empty.
classpath: simply points to a certain resource and if this is empty (where one would have expected it to exist) it would generate an error.


Note that "classpath*:" when combined with Ant-style patterns will only work reliably with at
least one root directory(IMPORTANT) 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 classpath*:META-INF/* will search as expected.


Darren Bishop said...

Clearly there's an important distinction between the two forms, but strangely for me it wasn't obvious and defaulted to thinking they were interchangeable.
Thanks for the explanation.

Anonymous said...

thanks for the detailed explanation

Free Domain Names @ .co.nr!