java与Spring中的资源加载

java Resource 资源加载: 

     xml properties  包名路径 

     1 ClassLoad.getResource(String str); 

     2 Class.getResource(Stirng str); 
     
     看第二种加载方式的内部一段代码 

Java代码   收藏代码
  1. private String resolveName(String name) {  
  2.         if (name == null) {  
  3.             return name;  
  4.         }  
  5.         if (!name.startsWith("/")) {  
  6.             Class c = this;  
  7.             while (c.isArray()) {  
  8.                 c = c.getComponentType();  
  9.             }  
  10.             String baseName = c.getName();  
  11.             int index = baseName.lastIndexOf('.');  
  12.             if (index != -1) {  
  13.                 name = baseName.substring(0, index).replace('.''/')  
  14.                     +"/"+name;  
  15.             }  
  16.         } else {  
  17.             name = name.substring(1);  
  18.         }  
  19.         return name;  
  20.     }  


这就说明了 

1最终都是通过ClassLoad进行加载的 

2第二种方式是可以使用相对路径的,也就是资源相对于本类路径下的路径 
如果本来的包名为com.xx.test 下面有一个xx.xml文件和xx.java类。 
我们在xx.java类中想加载xx.xml。那么它的路径可以写为: 
/com/xx/xx.xml 或者是 xx.cml。 

同样的道理如果test包下面还有一个text包,这个包里面有一个yy.java 
那么相对路径就是../xx.xml就可以加载到资源。 

如果是ClassLoad.getResource(str);这种方式只能写路径的全限定名,不加“/”,也就是com/xx/xx.xml 

后又测试了几种文件xml properties 和包路径是可以的 但是java类却不行后追踪源码发现 

Java代码   收藏代码
  1. private ClassLoader parent;  
  2. public URL getResource(String name) {  
  3.     URL url;  
  4.     if (parent != null) {  
  5.         url = parent.getResource(name);  
  6.     } else {  
  7.         url = getBootstrapResource(name);  
  8.     }  
  9.     if (url == null) {  
  10.         url = findResource(name);  // return null  
  11.     }  
  12.     return url;  
  13.    }  



     这里我们可以看到加载顺序是会始终找到它的父类或者祖先类直到没有了父类为止 
然后到Bootstrap(基本类装入器是不能有java代码实例化的,由JVM控制)加载。 
     
部分源码: 

Java代码   收藏代码
  1. private static URL getBootstrapResource(String name) {  
  2.        try {  
  3.            // If this is a known JRE resource, ensure that its bundle is  
  4.            // downloaded.  If it isn't known, we just ignore the download  
  5.            // failure and check to see if we can find the resource anyway  
  6.            // (which is possible if the boot class path has been modified).  
  7.            sun.jkernel.DownloadManager.getBootClassPathEntryForResource(name);  
  8.        } catch (NoClassDefFoundError e) {  
  9.            // This happens while Java itself is being compiled; DownloadManager  
  10.            // isn't accessible when this code is first invoked.  It isn't an  
  11.            // issue, as if we can't find DownloadManager, we can safely assume  
  12.            // that additional code is not available for download.  
  13.        }  
  14.     URLClassPath ucp = getBootstrapClassPath();  
  15.     Resource res = ucp.getResource(name);  
  16.     return res != null ? res.getURL() : null;  
  17.    }  




测试代码: 
     测试类结构图: 

Java代码   收藏代码
  1.   com.xx.MyTest  
  2.     - com.xx.text.MyTestC  
  3.   appconfig.xml  
  4.   appconfig.properties  
  5.   
  6. public class MyTest {  
  7.   
  8.     @Test  
  9.     public void testResource() throws IOException {  
  10.   
  11.           
  12.         URL url3 = this.getClass().getResource("appconfig.xml");  
  13.         //or URL url3 = this.getClass().getResource("/com/xx/MyTest/appconfig.xml");  
  14.         URL url4 = this.getClass().getClassLoader().getResource("com/xx/MyTest/appconfig.properties");  
  15.   
  16.         System.out.println(url4.getFile());  
  17.         System.out.println(url3.getFile());  
  18.     }  
  19.   
  20.   
  21.     public URL printResourceCs(String str) throws IOException {  
  22.   
  23.         URL url3 = this.getClass().getResource(str);  
  24.   
  25.         System.out.println(url3.getFile());  
  26.   
  27.         return url3;  
  28.     }  
  29.   
  30.     public URL printResourceCL(String str) throws IOException {  
  31.   
  32.         URL url3 = this.getClass().getClassLoader().getResource(str);  
  33.   
  34.         System.out.println(url3.getFile());  
  35.   
  36.         return url3;  
  37.     }  
  38. }  



为了测试继承关系得到的基础url: 

Java代码   收藏代码
  1. public class MyTestC extends MyTest {  
  2.       
  3.     @Test  
  4.     public void testA() throws IOException {  
  5.         Assert.assertNotNull(printResourceCs("../appConfig.xml"));  
  6.         Assert.assertNotNull(printResourceCL("sl/ewfs/dms/action/appConfig.xml"));  
  7.     }  
  8. }  




应用: 

1 当我们需要加载xml,或者properties 配置文件时,有时候需要这样做。 

2 利用ClassLoad我们可以得到项目运行是的根目录getClassLoader().getResource("")即可 

附上加载properties 代码: 

Java代码   收藏代码
  1.        
  2. public void  loadPropertiesFromXML(String XMLPath) throws IOException {        URL url = getClass().getResource(XMLPath);  
  3.         InputStream is = null;  
  4.         URLConnection con = null;  
  5.         Properties p = new Properties();  
  6.         try {  
  7.             con = url.openConnection();  
  8.             p.loadFromXML(is = con.getInputStream());            //p.load(is = con.getInputStream());        } catch (IOException e) {  
  9.             throw e;  
  10.         } finally {  
  11.             if (is != null) {  
  12.                 try {  
  13.                     is.close();  
  14.                 } catch (IOException e) {  
  15.                     e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.  
  16.                 }  
  17.             }  
  18.   
  19.         }  
  20.     }  



再来看看Spring的资源加载: 
Spring的Resource接口代表底层外部资源,提供了对底层外部资源的一致性访问接口。 

对应层次图 

 

uml: 



其中,最常用的有四个: 

ClassPathResource:通过 ClassPathResource 以类路径的方式进行访问; 

FileSystemResource:通过 FileSystemResource 以文件系统绝对路径的方式进行访问; 

ServletContextResource:通过 ServletContextResource 以相对于Web应用根目录的方式进行访问; 

UrlResource :通过java.net.URL来访问资源,当然它也支持File格式,如“file:”。 

当然你也可以通过ApplicationContext 来取得Resource 
这会带来少许的方便,因为当你可以实现ApplicationContextAware来方便的得到ApplicationContext 
然后使用 

Java代码   收藏代码
  1. applicationContext.getResource("commons/lib/xx/xx.xx").getFile().getAbsolutePath()  



就可以得到资源的绝对路径 

下段是applicationContext getResource 的代码 

Java代码   收藏代码
  1. String CLASSPATH_URL_PREFIX = “classPath”;  
  2. public Resource getResource(String location) {  
  3.           Assert.notNull(location, "Location must not be null");  
  4.           if (location.startsWith(CLASSPATH_URL_PREFIX)) {  
  5.                return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());  
  6.           }  
  7.           else {  
  8.                try {  
  9.                     // Try to parse the location as a URL...  
  10.                     URL url = new URL(location);  
  11.                     return new UrlResource(url);  
  12.                }  
  13.                catch (MalformedURLException ex) {  
  14.                     // No URL -> resolve as resource path.  
  15.                     return getResourceByPath(location);  
  16.                }  
  17.           }  
  18.      }  





Resource参考: 
http://wade6.iteye.com/blog/1706941 

http://jinnianshilongnian.iteye.com/blog/1416319 

http://jinnianshilongnian.iteye.com/blog/1416320 

http://jinnianshilongnian.iteye.com/blog/1416321 

http://jinnianshilongnian.iteye.com/blog/1416322 

java 类加载机制:http://www.ibm.com/developerworks/cn/java/j-lo-classloader/

猜你喜欢

转载自fengbin2005.iteye.com/blog/2288114