使用Spring的ClassPathResource加载资源文件

📅 2026/7/28 19:32:10 👁️ 阅读次数 📝 编程学习
使用Spring的ClassPathResource加载资源文件

参考博客链接:https://www.cnblogs.com/ruiati/p/6225093.html

publicclassTestClassPathResource{@TestpublicvoidtestResouce(){ClassLoader loader=Thread.currentThread().getContextClassLoader();System.out.println(loader.getResource("").getPath());System.out.println(this.getClass().getResource("").getPath());System.out.println(this.getClass().getResource("/").getPath());System.out.println(System.getProperty("user.dir"));try{String filePath=newClassPathResource("../resources/application.yml").getFile().getAbsolutePath();System.out.println(filePath);}catch(IOExceptione){e.printStackTrace();}}}

Class.getResource("")获取的是相对于当前类的相对路径

Class.getResource("/")获取的是classpath的根路径

ClassLoader.getResource("")获取的是classpath的根路径

在创建ClassPathResource对象时,我们可以指定是按Class的相对路径获取文件还是按ClassLoader来获取。