一、在用eclipse構建的項目中,根目錄下會有.classpath文件中指定classpath路徑。
說明:kind="src"所指的路徑就是classpath路徑。
二、在用idea構建項目中,會在根目錄下的.idea/moudles/xxx_main.iml文件中指定classpath路徑。
說明:url所指的路徑就是classpath路徑。
三、Java中獲取classpath目錄下資源文件的幾種方法的區別和聯繫
聯繫:無論哪一種方式獲取最後都是統一委派給ClassLoader類加載器來查找。
區別1、this.class.getResource("").getPath()與this.class.getResource("/").getPath()
說明:Class的getResource方法會根據傳入的參數適當處理,當傳入空字符串時,會查找到當前類的路徑,當以/開頭,程序會跳過/查找後面的路徑。
區別2、this.class.getResource("").getPath()與this.class.getClassLoader().getResource("").getPath()
說明:前者會對輸入的參數做處理後者會不對參數做處理並且空字符串表示的是classpath的根路徑。
四、Springboot在初始化環境時會添加很多監聽器,其中ConfigFileApplicationListener監聽器會對application.properties中的配置進行加載,該監聽器默認的搜索路徑有四個是保存在DEFAULT_SEARCH_LOCATIONS屬性中。
五、Linux與Windows通用獲取資源文件方式
Windows測試結果:
Main.class.getResource("").getPath() --> /E:/xxx/classpath/out/production/classes/xxx/xxx/classpath/
Main.class.getResource("/application.properties").getPath() --> /E:/xxx/classpath/out/production/resources/application.properties
Thread.currentThread().getContextClassLoader().getResource( "application.properties" ).getPath() --> /E:/xxx/classpath/out/production/resources/application.properties
Linux測試結果:
Main.class.getResource("").getPath() --> file:/home/xxx/classpath.jar!/com/htiiot/classpath/
Main.class.getResource("/application.properties").getPath() --> file:/home/xxx/classpath.jar!/application.properties
Thread.currentThread().getContextClassLoader().getResource( "application.properties" ).getPath() --> file:/home/xxx/classpath.jar!/application.properties