`
lohasle
  • 浏览: 253769 次
社区版块
存档分类
最新评论

java与Spring中的资源加载

阅读更多
java Resource 资源加载:

     xml properties  包名路径

     1 ClassLoad.getResource(String str);

     2 Class.getResource(Stirng str);
    
     看第二种加载方式的内部一段代码
private String resolveName(String name) {
        if (name == null) {
            return name;
        }
        if (!name.startsWith("/")) {
            Class c = this;
            while (c.isArray()) {
                c = c.getComponentType();
            }
            String baseName = c.getName();
            int index = baseName.lastIndexOf('.');
            if (index != -1) {
                name = baseName.substring(0, index).replace('.', '/')
                    +"/"+name;
            }
        } else {
            name = name.substring(1);
        }
        return name;
    }

这就说明了

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类却不行后追踪源码发现
 private ClassLoader parent;
 public URL getResource(String name) {
     URL url;
     if (parent != null) {
         url = parent.getResource(name);
     } else {
         url = getBootstrapResource(name);
     }
     if (url == null) {
         url = findResource(name);  // return null
     }
     return url;
    }


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

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



测试代码:
     测试类结构图:
  com.xx.MyTest
    - com.xx.text.MyTestC
  appconfig.xml
  appconfig.properties

public class MyTest {

    @Test
    public void testResource() throws IOException {

        
        URL url3 = this.getClass().getResource("appconfig.xml");
        //or URL url3 = this.getClass().getResource("/com/xx/MyTest/appconfig.xml");
        URL url4 = this.getClass().getClassLoader().getResource("com/xx/MyTest/appconfig.properties");

        System.out.println(url4.getFile());
        System.out.println(url3.getFile());
    }


    public URL printResourceCs(String str) throws IOException {

        URL url3 = this.getClass().getResource(str);

        System.out.println(url3.getFile());

        return url3;
    }

    public URL printResourceCL(String str) throws IOException {

        URL url3 = this.getClass().getClassLoader().getResource(str);

        System.out.println(url3.getFile());

        return url3;
    }
}


为了测试继承关系得到的基础url:
public class MyTestC extends MyTest {
    
    @Test
    public void testA() throws IOException {
        Assert.assertNotNull(printResourceCs("../appConfig.xml"));
        Assert.assertNotNull(printResourceCL("sl/ewfs/dms/action/appConfig.xml"));
    }
}



应用:

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

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

附上加载properties 代码:
     
public void  loadPropertiesFromXML(String XMLPath) throws IOException {        URL url = getClass().getResource(XMLPath);
        InputStream is = null;
        URLConnection con = null;
        Properties p = new Properties();
        try {
            con = url.openConnection();
            p.loadFromXML(is = con.getInputStream());            //p.load(is = con.getInputStream());        } catch (IOException e) {
            throw e;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }

        }
    }


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

对应层次图



uml:



其中,最常用的有四个:

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

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

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

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

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

applicationContext.getResource("commons/lib/xx/xx.xx").getFile().getAbsolutePath()
;

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

下段是applicationContext getResource 的代码
String CLASSPATH_URL_PREFIX = “classPath”;
public Resource getResource(String location) {
          Assert.notNull(location, "Location must not be null");
          if (location.startsWith(CLASSPATH_URL_PREFIX)) {
               return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
          }
          else {
               try {
                    // Try to parse the location as a URL...
                    URL url = new URL(location);
                    return new UrlResource(url);
               }
               catch (MalformedURLException ex) {
                    // No URL -> resolve as resource path.
                    return getResourceByPath(location);
               }
          }
     }




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/
  • 大小: 176.7 KB
  • 大小: 746 KB
分享到:
评论

相关推荐

    spring boot中配置mybatis热加载.zip

    spring boot中配置mybatis xml资源文件热加载的方法以及相关文件

    javaspring 培训教程 TP1.docx

    Java Spring 是一个开源的、轻量级的、高效的开发框架, 它可以帮助Java 开发人员快速开发各种应用程序。...详细阐述了 Spring 容器的加载过程, 以及依赖注入的实现原理。并且提供了一些基于 xml 配置和注 解的实例。

    Spring中文帮助文档

    6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点运算 7.2.3. AspectJ切入点表达式 7.2.4. 便利的切入...

    Spring攻略(第二版 中文高清版).part2

    3.10 Spring中的AspectJ加载时织入aspect 140 3.10.1 问题 140 3.10.2 解决方案 141 3.10.3 工作原理 141 3.11 在Spring中配置AspectJ aspect 146 3.11.1 问题 146 3.11.2 解决方案 146 3.11.3 工作...

    Spring攻略(第二版 中文高清版).part1

    3.10 Spring中的AspectJ加载时织入aspect 140 3.10.1 问题 140 3.10.2 解决方案 141 3.10.3 工作原理 141 3.11 在Spring中配置AspectJ aspect 146 3.11.1 问题 146 3.11.2 解决方案 146 3.11.3 工作...

    spring加载restful(文档+程序源码)

    spring加载restful(文档+程序源码) 通过REST风格体系架构,请求和响应都是基于资源表示的传输来构建的。资源是通过全局ID来标识的,这些ID一般使用的是一个统一资源标识符(URI)。客户端应用使用HTTP方法(如,...

    JAVA上百实例源码以及开源项目源代码

     Java 3DMenu 界面源码,有人说用到游戏中不错,其实平时我信编写Java应用程序时候也能用到吧,不一定非要局限于游戏吧,RES、SRC资源都有,都在压缩包内。 Java zip压缩包查看程序源码 1个目标文件 摘要:Java源码...

    JAVA上百实例源码以及开源项目

     Java 3DMenu 界面源码,有人说用到游戏中不错,其实平时我信编写Java应用程序时候也能用到吧,不一定非要局限于游戏吧,RES、SRC资源都有,都在压缩包内。 Java zip压缩包查看程序源码 1个目标文件 摘要:Java源码...

    Java基于SSM(Spring+SpringMVC+MyBatis)杏种质资源管理系统.zip

    8、 释放资源(resultSet、preparedstatement、connection)Spring MVC简介 基于java的实现MVC设计模式的请求驱动类型的轻量级Web框架,通过注解,无需实现任何接口,处理请求,支持restful。 三层结构:表现层、业务...

    Java基于SSM(Spring+SpringMVC+MyBatis)树品种资源数据管理系统.zip

    8、 释放资源(resultSet、preparedstatement、connection)Spring MVC简介 基于java的实现MVC设计模式的请求驱动类型的轻量级Web框架,通过注解,无需实现任何接口,处理请求,支持restful。 三层结构:表现层、业务...

    Java基于SSM(Spring+SpringMVC+MyBatis)中小型超市管理系统.zip

    8、 释放资源(resultSet、preparedstatement、connection)Spring MVC简介 基于java的实现MVC设计模式的请求驱动类型的轻量级Web框架,通过注解,无需实现任何接口,处理请求,支持restful。 三层结构:表现层、业务...

    Java基于SSM(Spring+SpringMVC+MyBatis)在线个人网站.zip

    8、 释放资源(resultSet、preparedstatement、connection)Spring MVC简介 基于java的实现MVC设计模式的请求驱动类型的轻量级Web框架,通过注解,无需实现任何接口,处理请求,支持restful。 三层结构:表现层、业务...

    Java基于SSM(Spring+SpringMVC+MyBatis)作业提交与批改程序.zip

    8、 释放资源(resultSet、preparedstatement、connection)Spring MVC简介 基于java的实现MVC设计模式的请求驱动类型的轻量级Web框架,通过注解,无需实现任何接口,处理请求,支持restful。 三层结构:表现层、业务...

    Java基于SSM(Spring+SpringMVC+MyBatis)实习支教中小学学校信息管理系统.zip

    8、 释放资源(resultSet、preparedstatement、connection)Spring MVC简介 基于java的实现MVC设计模式的请求驱动类型的轻量级Web框架,通过注解,无需实现任何接口,处理请求,支持restful。 三层结构:表现层、业务...

    Java资源包01

    LemonSMS 这个Java库可以让开发者在应用程序中集成使用GSM调制解调器或兼容电话来发送SMS消息。 远程桌面 Java Remote Desktop.tar Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、...

    Spring API

    6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点运算 7.2.3. AspectJ切入点表达式 7.2.4. 便利的切入...

    Spring.3.x企业应用开发实战(完整版).part2

    3.3.2 资源加载 3.4 BeanFactory和ApplicationContext 3.4.1 BeanFactory介绍 3.4.2 ApplicationContext介绍 3.4.3 父子容器 3.5 Bean的生命周期 3.5.1 BeanFactory中Bean的生命周期 3.5.2 ApplicationContext中Bean...

    java开源包4

    LemonSMS 这个Java库可以让开发者在应用程序中集成使用GSM调制解调器或兼容电话来发送SMS消息。 远程桌面 Java Remote Desktop.tar Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、...

    java开源包11

    LemonSMS 这个Java库可以让开发者在应用程序中集成使用GSM调制解调器或兼容电话来发送SMS消息。 远程桌面 Java Remote Desktop.tar Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、...

    java开源包101

    LemonSMS 这个Java库可以让开发者在应用程序中集成使用GSM调制解调器或兼容电话来发送SMS消息。 远程桌面 Java Remote Desktop.tar Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、...

Global site tag (gtag.js) - Google Analytics