How to find in classpath:spring

Source: Internet
Author: User

Spring can load files from classpath, such as the Bean's definition file, by specifying classpath*: with the classpath: prefix plus path. classpath*: Appears to load the same file from multiple jar Files. classpath: only the first file found is Loaded.

For example, the package ' com.test.rs ' in Resource1.jar has a ' jarappcontext.xml ' file that reads as Follows:

<bean name= "processorimpla" class= "com.test.spring.di.ProcessorImplA"/>

The package ' com.test.rs ' in Resource2.jar also has a ' jarappcontext.xml ' file that reads as Follows:

<bean id= "processorimplb" class= "com.test.spring.di.ProcessorImplB"/>

You can load the files in the two jar packages by using the following code

ApplicationContext CTX = new Classpathxmlapplicationcontext ("classpath*:com/test/rs/jarappcontext.xml");

If you write the following code, you can only find one of the XML files (the order depends on the load order of the jar Packages)

ApplicationContext CTX = new Classpathxmlapplicationcontext ("classpath:com/test/rs/jarappcontext.xml");

Classpath*: is used for multiple component (eventually released into different jar packages) in parallel development, the respective bean definition files according to certain rules: package+filename, The callers who use these component can load the files in.

Classpath*: loading uses the ClassLoader getResources() method, and if it is running on a different Java EE server, they may behave differently when working with the jar file because the application server provides its own ClassLoader Implementation. To test classpath*: Whether it is valid, you can test it with ClassLoader from the jar file in the classpath to load the file: getClass().getClassLoader().getResources("<someFileInsideTheJar>") . (the example above is the state running in Sun's Jre)

From Spring's source code, in the Pathmatchingresourcepatternresolver class, we can better understand its handling: if it starts with classpath*, it will traverse Classpath.

[java]View PlainCopy
  1. Protected resource[] findallclasspathresources (String Location) throws IOException {
  2. String Path = location;
  3. if (path.startswith ("/")) {
  4. Path = path.substring (1);
  5. }
  6. Enumeration resourceurls = getClassLoader (). getresources (path);
  7. set<resource> result = new linkedhashset<resource> (16);
  8. while (resourceurls.hasmoreelements ()) {
  9. URL url = (url) resourceurls.nextelement ();
  10. Result.add (convertclassloaderurl (url));
  11. }
  12. return Result.toarray (new Resource[result.size ()));
  13. }

http://blog.csdn.net/kkdelta/article/details/5560210, introduces all the matching names found in Java traversal classpath.

In addition, when loading resource, the meanings of the other prefixes are as follows: note that classpath* can only be used with the path specified by the configuration file and cannot be used in parameters used for getresource. such as Appcontext.getresource (" Classpath*:conf/bfactoryctx.xml ") will be abnormal.

prefix Example Description

Classpath

classpath:com/myapp/config.xml

Loaded from the Classpath.

File

file:/data/config.xml

As URL loaded from the file System.

http

http://myserver/logo.png

As URL Load.

(none)

/data/config.xml

According ApplicationContext to the Judgment.

From the source of spring can see the reason: if it is classpath: start, load from classpath, otherwise try the url, if failed, call Getresourcebypath

[java]View PlainCopy
  1. Public Resource GetResource (String Location) {
  2. Assert.notnull (location, "must is not null");
  3. if (location.startswith (classpath_url_prefix)) {
  4. return new Classpathresource (location.substring (classpath_url_prefix.length ()), getclassloader ());
  5. }
  6. else {
  7. try {
  8. //Try to parse the location as a URL ...
  9. URL url = new URL (location);
  10. return New Urlresource (url);
  11. }
  12. catch (malformedurlexception Ex) {
  13. //No URL, Resolve as Resource path.
  14. return Getresourcebypath (location);
  15. }
  16. }
  17. }


Getresourcebypath will be overwritten by different ApplicationContext Implementations.

If the genericwebapplicationcontext is covered as follows:

[java]View PlainCopy
  1. Protected Resource Getresourcebypath (String Path) {
  2. return new Servletcontextresource (this.servletcontext, path);
  3. }
  4. If the filesystemxmlapplicationcontext is covered as follows:
  5. Protected Resource Getresourcebypath (String Path) {
  6. if (path! = null && path.startswith ("/")) {
  7. Path = path.substring (1);
  8. }
  9. return New Filesystemresource (path);
  10. }

It is still common in Java to read files when loading from a file:

The way to get InputStream as Classpathresource is to use class Loader.

[java]View PlainCopy
    1. Public InputStream getInputStream () throws IOException {
    2. InputStream is;
    3. if (this.clazz! = Null) {
    4. is = This.clazz.getResourceAsStream (this.path);
    5. }

The way to get inputstream, as filesystemresource, is to use Fileinputstream.

Public InputStream getInputStream () throws IOException {
return new FileInputStream (this.file);
}

The way to get inputstream, as servletcontextresource, is to use Servletcontext.getresourceasstream.

[java]View PlainCopy
      1. public inputstream getinputstream ()  throws ioexception {  
      2.      inputstream is = this.servletcontext.getresourceasstream ( Span class= "keyword" >this.path)   
      3.     if  (is == null)  {  
      4.         throw new  filenotfoundexception ( "could not open "  + getdescription () );   
      5.     }  
      6.      return is;  

How to find in classpath:spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.