java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java 资源加载

Java中资源加载的方法及Spring的ResourceLoader应用小结

作者:冷风扇666

在Java开发中,资源加载是一个基础而重要的操作,这篇文章主要介绍了深入理解Java中资源加载的方法及Spring的ResourceLoader应用,本文通过实例代码演示了通过ClassLoader和Class获取资源的内容,以及使用Spring的ResourceLoader加载多个资源的过程,需要的朋友可以参考下

在Java开发中,资源加载是一个基础而重要的操作。本文将深入探讨Java中两种常见的资源加载方式:ClassLoader的getResource方法和Class的getResource方法,并介绍Spring框架中的ResourceLoader的应用。

1. 资源加载的两种方式

1.1 ClassLoader的getResource方法

URL resourceFromClass = classLoader.getResource("demo.txt");

ClassLoadergetResource方法是通过当前类的ClassLoader实例来加载资源。路径是相对于classpath的,可以轻松获取单个资源。需要注意的是,路径不要以"/"开头,否则可能返回null。

1.2 Class的getResource方法

URL resourceFromClassWithPath = aClass.getResource("dir/demo.txt");

ClassgetResource方法通过当前类来加载资源,路径是相对于当前类所在的包。如果资源名以"/"开头,会以classpath为基准路径加载资源。这种方式可以方便地获取当前类包内的资源。

2. 获取批量资源

Enumeration<URL> resources = classLoader.getResources("META-INF/MANIFEST.MF");

通过ClassLoadergetResources方法,可以获取指定路径下的所有资源,返回一个Enumeration对象。这对于需要处理多个配置文件或元数据文件的场景非常有用。

3. Spring的ResourceLoader和ResourcePatternResolver

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] springResources = resolver.getResources("classpath:/spring/*.xml");

Spring框架提供了ResourceLoaderResourcePatternResolver接口,封装了资源加载的方法。在上述代码中,通过PathMatchingResourcePatternResolver实例,可以使用通配符获取classpath下的所有xml文件。这对于加载多个配置文件非常方便。

4. 完整示例

package com.lfsun.resources;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
public class MyResource {
    public static void main(String[] args) throws Exception {
        // 获取单个资源
        // 获取当前类的Class对象
        Class<MyResource> aClass = MyResource.class;
        // 获取当前类的ClassLoader
        ClassLoader classLoader = aClass.getClassLoader();
        // 使用ClassLoader获取资源,路径相对于classpath
        URL resourceFromClass = classLoader.getResource("demo.txt");
        // 使用Class获取资源,路径相对于当前类所在的包
        URL resourceFromClassWithPath = aClass.getResource("dir/demo.txt");
        // 输出资源内容
        if (resourceFromClass != null) {
            byte[] bytes = readBytesFromStream(resourceFromClass.openStream());
            System.out.println("ClassLoader获取的资源内容: " + new String(bytes));
        }
        if (resourceFromClassWithPath != null) {
            byte[] bytes = readBytesFromStream(resourceFromClassWithPath.openStream());
            System.out.println("Class获取的资源内容: " + new String(bytes));
        }
        // 获取批量资源
        Enumeration<URL> resources = classLoader.getResources("META-INF/MANIFEST.MF");
        while (resources.hasMoreElements()) {
            URL manifestResource = resources.nextElement();
            System.out.println("Manifest资源: " + manifestResource);
        }
        // 使用Spring的ResourceLoader和ResourcePatternResolver
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 使用通配符获取classpath下的所有xml文件
        Resource[] springResources = resolver.getResources("classpath:/spring/*.xml");
        // 输出Spring资源内容
        for (Resource springResource : springResources) {
            InputStream stream = springResource.getInputStream();
            byte[] bytes = readBytesFromStream(stream);
            System.out.println("Spring资源内容: " + new String(bytes));
        }
    }
    private static byte[] readBytesFromStream(InputStream stream) throws IOException {
        StringBuilder buffer = new StringBuilder();
        byte[] bytes = new byte[1024];
        int bytesRead;
        while ((bytesRead = stream.read(bytes)) != -1) {
            buffer.append(new String(bytes, 0, bytesRead));
        }
        return buffer.toString().getBytes();
    }
}

输出:

D:\Config\java-17\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2023.2.4\lib\idea_rt.jar=62858:D:\Program Files\JetBrains\IntelliJ IDEA 2023.2.4\bin" -Dfile.encoding=UTF-8 -classpath D:\Users\Administrator\IdeaProjects\lfsun-study-java17\lfsun-study-resources\target\classes;D:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter\3.2.1\spring-boot-starter-3.2.1.jar;D:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot\3.2.1\spring-boot-3.2.1.jar;D:\Users\Administrator\.m2\repository\org\springframework\spring-context\6.1.2\spring-context-6.1.2.jar;D:\Users\Administrator\.m2\repository\org\springframework\spring-aop\6.1.2\spring-aop-6.1.2.jar;D:\Users\Administrator\.m2\repository\org\springframework\spring-beans\6.1.2\spring-beans-6.1.2.jar;D:\Users\Administrator\.m2\repository\org\springframework\spring-expression\6.1.2\spring-expression-6.1.2.jar;D:\Users\Administrator\.m2\repository\io\micrometer\micrometer-observation\1.12.1\micrometer-observation-1.12.1.jar;D:\Users\Administrator\.m2\repository\io\micrometer\micrometer-commons\1.12.1\micrometer-commons-1.12.1.jar;D:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\3.2.1\spring-boot-autoconfigure-3.2.1.jar;D:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter-logging\3.2.1\spring-boot-starter-logging-3.2.1.jar;D:\Users\Administrator\.m2\repository\ch\qos\logback\logback-classic\1.4.14\logback-classic-1.4.14.jar;D:\Users\Administrator\.m2\repository\ch\qos\logback\logback-core\1.4.14\logback-core-1.4.14.jar;D:\Users\Administrator\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.21.1\log4j-to-slf4j-2.21.1.jar;D:\Users\Administrator\.m2\repository\org\apache\logging\log4j\log4j-api\2.21.1\log4j-api-2.21.1.jar;D:\Users\Administrator\.m2\repository\org\slf4j\jul-to-slf4j\2.0.9\jul-to-slf4j-2.0.9.jar;D:\Users\Administrator\.m2\repository\jakarta\annotation\jakarta.annotation-api\2.1.1\jakarta.annotation-api-2.1.1.jar;D:\Users\Administrator\.m2\repository\org\springframework\spring-core\6.1.2\spring-core-6.1.2.jar;D:\Users\Administrator\.m2\repository\org\springframework\spring-jcl\6.1.2\spring-jcl-6.1.2.jar;D:\Users\Administrator\.m2\repository\org\yaml\snakeyaml\2.2\snakeyaml-2.2.jar;D:\Users\Administrator\.m2\repository\org\slf4j\slf4j-api\2.0.9\slf4j-api-2.0.9.jar com.lfsun.resources.MyResource
ClassLoader获取的资源内容: 这是 demo.txt 的内容。

Class获取的资源内容: 这是 dir/demo.txt 的内容。

Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/boot/spring-boot-starter/3.2.1/spring-boot-starter-3.2.1.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/boot/spring-boot/3.2.1/spring-boot-3.2.1.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/spring-context/6.1.2/spring-context-6.1.2.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/spring-aop/6.1.2/spring-aop-6.1.2.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/spring-beans/6.1.2/spring-beans-6.1.2.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/spring-expression/6.1.2/spring-expression-6.1.2.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/io/micrometer/micrometer-observation/1.12.1/micrometer-observation-1.12.1.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/io/micrometer/micrometer-commons/1.12.1/micrometer-commons-1.12.1.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/3.2.1/spring-boot-autoconfigure-3.2.1.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/boot/spring-boot-starter-logging/3.2.1/spring-boot-starter-logging-3.2.1.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/ch/qos/logback/logback-classic/1.4.14/logback-classic-1.4.14.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/ch/qos/logback/logback-core/1.4.14/logback-core-1.4.14.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.21.1/log4j-to-slf4j-2.21.1.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/apache/logging/log4j/log4j-api/2.21.1/log4j-api-2.21.1.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/slf4j/jul-to-slf4j/2.0.9/jul-to-slf4j-2.0.9.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/jakarta/annotation/jakarta.annotation-api/2.1.1/jakarta.annotation-api-2.1.1.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/spring-core/6.1.2/spring-core-6.1.2.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/springframework/spring-jcl/6.1.2/spring-jcl-6.1.2.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/yaml/snakeyaml/2.2/snakeyaml-2.2.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Users/Administrator/.m2/repository/org/slf4j/slf4j-api/2.0.9/slf4j-api-2.0.9.jar!/META-INF/MANIFEST.MF
Manifest资源: jar:file:/D:/Program%20Files/JetBrains/IntelliJ%20IDEA%202023.2.4/lib/idea_rt.jar!/META-INF/MANIFEST.MF
Spring资源内容: <!-- config1.xml -->
<beans>
    <bean id="bean1" class="com.lfsun.resources.entity.Bean1"/>
</beans>

Spring资源内容: <!-- config2.xml -->
<beans>
    <bean id="bean2" class="com.lfsun.resources.entity.Bean2"/>
</beans>

Process finished with exit code 0

代码结构:

以上输出演示了通过ClassLoader和Class获取资源的内容,以及使用Spring的ResourceLoader加载多个资源的过程。

到此这篇关于深入理解Java中资源加载的方法及Spring的ResourceLoader应用的文章就介绍到这了,更多相关Java 资源加载内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文