15

I've seen some Spring code that read config files and other resources directly off the runtime classpath using the classpath:/some/path/to/resource URL protocol.

Is this a Spring construct or a Java construct?

I can't find any documentation besides this question - URL to load resources from the classpath in Java, which doesn't indicate either way.

If it's a Java construct, can anyone point me to its official documentation?

Community
  • 1
  • 1
IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756
  • 1
    I suggest to read about `ResourceLoader` abstraction: http://static.springsource.org/spring/docs/3.0.x/reference/resources.html#resources-resourceloader – Slava Semushin Aug 22 '12 at 20:59

2 Answers2

13

Well you can always register URL handlers. Java also has a file:/// and jar: handler. Also class.getResource will by default read from the classpath.

http://code.google.com/p/madura-classpath-protocol-handler/

apparently it is a spring feature.

"You can see these standard handlers, and associated implementation classes,in the JDK's RT.JAR file. Look for classes whose fully-qualified name starts with sun.net.www.protocol.For example,the class sun.net.www.protocol.http.Handler defines the HTTP protocol handler. Class sun.net.www.protocol.ftp.Handler defines the FTP protocol handler class."

http://java.sun.com/developer/onlineTraining/protocolhandlers/

Trying to use classpath: in Java 1.6 results in:

Exception in thread "main" java.net.MalformedURLException: unknown protocol: classpath

Joman68
  • 2,248
  • 3
  • 34
  • 36
Markus Mikkolainen
  • 3,397
  • 18
  • 21
  • 2
    Cool tips! I didn't know you could register your own handlers (+1)! But do you know if `classpath` is a URL handler defined/registered by Spring, or if it ships with Java? Thanks again! – IAmYourFaja Aug 17 '12 at 13:22
  • I think it is a builtin spring feature (looking at that link there) – Markus Mikkolainen Aug 17 '12 at 13:28
7

classpath: is specific to spring. Spring's resource resolving mechanism (ie. PathMatchingResourcePatternResolver or other imlementations) knows about the "classpath:" and "classpath*:" prefixes.

It takes that and resolves into ClassPathResource object(s), which happen to implement springs Resource interface.

The Resource interface, among other things, has a getInputStream() method which can be used to get the contents, without having to be aware of what type of resource it is.

This is entirely separate from any URL protocol handling, so you won't necessarily be able to directly add this as a protocol handler.

However, you may be able to make some use of the ClassPathResource class itself as part of your protocol handler.

AdrieanKhisbe
  • 3,899
  • 8
  • 37
  • 45
Matt
  • 11,523
  • 2
  • 23
  • 33
  • Spring documentation on `classpath:`: https://docs.spring.io/spring-framework/docs/3.0.x/spring-framework-reference/html/resources.html – Joman68 Mar 09 '22 at 01:41