一: 理解根目錄
<value>classpath*:/application.properties</value> <value>classpath:/application.properties</value>
這里的classpath怎么理解呢,其實指的就是根目錄,關於根目錄,需要了解:
(1): src不是classpath, WEB-INF/classes,lib才是classpath,WEB-INF/ 是資源目錄, 客戶端不能直接訪問。
(2): WEB-INF/classes目錄存放src目錄java文件編譯之后的class文件、xml、properties等資源配置文件,這是一個定位資源的入口。
(3): 引用classpath路徑下的文件,只需在文件名前加classpath:
<param-value>classpath:applicationContext-*.xml</param-value>
<!-- 引用其子目錄下的文件,如 -->
<param-value>classpath:context/conf/controller.xml</param-value>
(4): lib和classes同屬classpath,兩者的訪問優先級為: lib>classes。
(5): classpath 和 classpath* 區別:
classpath:只會到你的class路徑中查找找文件;
classpath*:不僅包含class路徑,還包括jar文件中(class路徑)進行查找。
二:this.getClass().getResourceAsStream和this.getClass().getClassLoader().getResourceAsStream的區別
(1)關於getClass().getClassLoader()
InputStream is = this.getClass().getClassLoader().getResourceAsStream("helloworld.properties");
其中this.getClass()和getClassLoader()都是什么意思呀.?
getClass():取得當前對象所屬的Class對象
getClassLoader():取得該Class對象的類裝載器
public void readProperty(){ //從當前類所在包下加載指定名稱的文件,getClass是到當前列 InputStream in = this.getClass().getResourceAsStream("biabc.properties"); // 從classpath根目錄下加載指定名稱的文件,這是因為/即代表根目錄 // InputStream in = this.getClass().getResourceAsStream("/abc.properties"); //從classpath根目錄下加載指定名稱的文件,這是因為getClassLoader就會到根目錄上 // InputStream in = this.getClass().getClassLoader().getResourceAsStream("abc.properties"); Properties properties = new Properties(); // 使用properties對象加載輸入流 try { properties.load(in); } catch (IOException e) { e.printStackTrace(); } //獲取key對應的value值 System.out.println(properties.getProperty( "a")); }
文章摘自: https://blog.csdn.net/h2604396739/article/details/83860334