【JAVA笔记——术】GetResource 实现方式

直接上代码

System.out.println(ClassLoaderTest.class.getResource(""));
System.out.println(ClassLoaderTest.class.getResource("/"));
System.out.println(ClassLoaderTest.class.getResource("\\"));
System.out.println(ClassLoaderTest.class.getResource("test.properties"));

System.out.println();

System.out.println(ClassLoader.getSystemResource(""));
System.out.println(ClassLoader.getSystemResource("/"));
System.out.println(ClassLoader.getSystemResource("\\"));
System.out.println(ClassLoader.getSystemResource("com/turing"));

System.out.println();

        System.out.println(ClassLoaderTest.class.getClassLoader().getResource(""));
        System.out.println(ClassLoaderTest.class.getClassLoader().getResource("/"));
        System.out.println(ClassLoaderTest.class.getClassLoader().getResource("\\"));
        System.out.println(ClassLoaderTest.class.getClassLoader().getResource("test.properties"));

运行结果如下

file:/E:/WorkSpace/Eclipse/Test/bin/com/turing/classloader/
file:/E:/WorkSpace/Eclipse/Test/bin/
file:/E:/WorkSpace/Eclipse/Test/bin/com/turing/classloader/%5c
null

file:/E:/WorkSpace/Eclipse/Test/bin/
null
file:/E:/WorkSpace/Eclipse/Test/bin/%5c
file:/E:/WorkSpace/Eclipse/Test/bin/com/turing

file:/E:/WorkSpace/Eclipse/Test/bin/
null
file:/E:/WorkSpace/Eclipse/Test/bin/%5c
file:/E:/WorkSpace/Eclipse/Test/bin/test.properties

结果比较明显,总结如下:

1 Class.getResource是从class所属目录进行加载,所以可以在多个资源文件时采用这种加载方式例如iBastis的Mapper加载

/
    /src/main/java
        /com.turing.entity
            Info.java
        /com.turing.dao
            InfoDao.java
        /com.turing.daoImpl
            InfoDaoImpl.java
    /src/main/resources
        /com
            /turing
                /entity
                    InfoMapper.xml

Resources文件,在构建之后都合并在ClassPath内,所以可以采用这种方式进行分散装配

2 ClassLoader.getSystemResource(“”)是从ClassPath获取路径
3 ClassLoaderTest.class.getClassLoader().getResource(“”) 也是从ClassPath下获取路径,根据源码可以看到ClassLoader采用双亲委派模型获取Resource,因此推荐采用这种方式,当使用自定义ClassLoader时,可以灵活实现Resource装配

posted @ 2016-06-13 11:33  写昵称不如写代码  阅读(135)  评论(0编辑  收藏  举报