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

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
分享到:
评论

相关推荐

    Java中Spring获取bean方法小结

    - **ApplicationContext** 是BeanFactory的扩展,增加了更多面向应用的功能,如国际化、事件处理、资源加载等。它通常被开发者直接使用,因为它提供了更为便捷的API和更丰富的功能。 2. **获取Bean的方式** - **...

    Spring中使用classpath加载配置文件浅析

    在Spring框架中,classpath加载配置文件是应用开发中常见的操作。Spring框架提供了灵活的方式来加载位于classpath中的XML配置文件,这对于项目的模块化和可维护性至关重要。本文将详细分析Spring通过classpath加载...

    Spring动态加载配置文件

    在Spring框架中,动态加载配置文件是一项重要的功能,它使得开发者在开发过程中无需重启应用就能实时更新配置,极大地提高了开发效率。热部署方案是这一功能的具体应用,它允许我们在不中断服务的情况下,对应用程序...

    java spring潜艇游戏源代码

    - `img`:可能存放游戏中的图像资源,如潜艇、背景、图标等,这些资源被加载到程序中,用于构建游戏视觉效果。 - `.idea`:这是IDE的配置文件夹,包含项目的各种设置、模块信息和运行配置。 - `out`:这是IDE编译...

    spring boot中配置mybatis热加载.zip

    下面将详细介绍如何在Spring Boot中配置MyBatis以实现XML资源文件的热加载。 首先,我们需要在Spring Boot项目的`pom.xml`或`build.gradle`文件中添加MyBatis和其Spring Boot starter的依赖。如果是Maven项目,添加...

    Java Spring框架依赖包

    Java Spring框架是一个广泛使用的开源应用程序框架,主要用于简化Java企业级应用的开发。它以其模块化、松耦合的架构而闻名,提供了丰富的功能,包括依赖注入(DI)、面向切面编程(AOP)、数据访问、Web应用支持...

    JAVA-spring学习资源之编程实现操作系统匹配条件

    这个“JAVA-spring学习资源之编程实现操作系统匹配条件”提供了如何在Spring应用中实现这一功能的教学资料。下面将详细介绍这个主题,并提供相关的知识点。 首先,Java中的`System.getProperty("os.name")`方法可以...

    Java面试 spring知识点 线程池 面试题

    而ApplicationContext则是在Bean工厂的基础上扩展,提供了更多的企业级功能,如资源加载、国际化支持等。理解Bean的生命周期也是关键,包括初始化、活跃状态、销毁等阶段,面试中可能会询问如何自定义Bean的生命周期...

    spring 启动时加载不同的文件

    - 将选定的文件内容合并到`Properties`对象中,并通过父类的`processProperties`方法加载到Spring容器中。 **5. setGollfPropFiles方法实现** ```java protected void processProperties...

    Spring Boot 全局懒加载机制.docx

    Spring Boot 2.2及更高版本引入了一个全局懒加载机制,允许用户通过配置开启整个应用的bean懒加载,以优化启动时间和资源利用。 在传统的Spring应用中,我们可以通过在bean定义上添加`@Lazy`注解来实现单个bean的懒...

    Java反射_Spring IOC

    Java反射和Spring IOC是Java开发中的两个重要概念,它们在构建灵活、可扩展的应用程序时起着关键作用。本文将深入探讨这两个主题,并提供相关的学习资源。 首先,让我们了解一下Java反射。Java反射机制是Java语言的...

    Restlet与Spring 集成

    `restRoute`是一个Spring路由器,通过`attachments`映射将URL路径与处理资源的Spring Bean关联。 - **userContext.xml**:在这个文件中,定义了一个名为`userRoute`的Spring路由器,用于处理 `/user/addUser` 路径...

    Spring-MVC-step-by-step.zip_Java MVC spring_Java spring mvc_sp

    Spring MVC提供了国际化的支持,可以根据用户的选择动态加载不同语言的资源文件。同时,还可以配置主题来改变UI的样式。 十一、单元测试与MockMvc Spring MVC提供MockMvc工具,可以在不依赖Web服务器的情况下对...

    spring加载

    前者是最基础的bean工厂,而ApplicationContext不仅包含了BeanFactory的功能,还添加了资源加载、消息解析、事件发布等功能,更适合企业级应用。 三、Bean的生命周期 1. **实例化**:Spring通过反射或CGLIB动态...

    spring5.0.2中文官网文档

    它既可以加载XML文件中的配置信息,也可以加载基于注解或Java代码的配置。 除了IoC容器,Spring框架还提供了面向方面的编程(AOP)能力,它使得开发者可以定义“切面”来为跨多个点的对象提供额外的行为,而不必...

    Java与spring-boot实现分布式高并发秒杀系统

    在构建分布式高并发秒杀系统时,...以上就是构建Java与Spring-Boot实现的分布式高并发秒杀系统的一些关键技术点。在实际开发过程中,还需要根据业务需求和系统规模灵活调整策略,不断优化,以提供高效稳定的秒杀服务。

    Spring2.5中文手册

    Spring框架是中国Java开发领域中不可或缺的一部分,特别是在企业级应用开发中。Spring 2.5版本是该框架的一个重要里程碑,引入了许多新特性和改进。这个`Spring2.5中文手册`是一个非常有价值的参考资料,帮助开发者...

    spring源码包.zip

    `spring-context`还支持AOP(面向切面编程)、事件传播、国际化以及资源加载等功能。 `spring-webmvc`模块则是Spring MVC(Model-View-Controller)的实现,是Web应用的核心组件。它处理HTTP请求,通过...

    java开发spring开发的一些jar包

    1. **spring-core.jar**:这是Spring框架的基础,包含了IoC容器的基本实现和核心工具类,提供资源加载、对象封装和转换服务等功能。 2. **spring-beans.jar**:该jar包提供了BeanFactory接口,它是Spring IoC容器的...

    spring5资源.zip

    - spring-context.jar:ApplicationContext容器,包含事件发布、资源加载、国际化等功能。 - spring-beans.jar:Bean工厂和bean定义相关。 - spring-aop.jar:AOP模块,实现切面编程。 - spring-aspects.jar:对于...

Global site tag (gtag.js) - Google Analytics