首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring @Value 無法讀取 properties ?三大常見原因與診斷全流程

     編輯:Java 綜合教學

Spring @Value 無法讀取 properties ?三大常見原因與診斷全流程

現象一:Controller 注入失敗

原因:Controller 由 DispatcherServlet 建立,屬於子容器,只能讀取 servlet-context.xml(或 *-servlet.xml)中定義的 PropertyPlaceholderConfigurer。

修復:在對應 Servlet 配置文件添加:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
    <list>
      <value>classpath:jdbc.properties</value>
      <value>classpath:config.properties</value>
    </list>
  </property>
  <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

現象二:Service 讀取到錯誤/空值

原因:Classpath 下存在同名 config.properties(如 JAR 包內部與外部配置目錄各一份),Spring 預設只載入第一個。

現象日誌:

Loading properties file from URL [jar:file:/.../xxxx-common-1.5.7.jar!/config.properties]
Loading properties file from URL [file:/home/admin/creative-task/conf/config.properties]

修復:使用 classpath*: 前綴強制合併所有同名文件:

<context:property-placeholder ignore-unresolvable="true" 
  location="classpath:/jdbc.properties, classpath*:/config.properties"/>

診斷三步法

  1. 確認文件是否載入:啟動日志搜 Loading properties file from URL,缺失則檢查路徑拼寫、打包結構。
  2. 確認屬性是否解析:開啟 DEBUG 日志 org.springframework.core.env.PropertySourcesPropertyResolver,觀察 Found key 'xxx' in [localProperties]。
  3. Key 拼寫核對:若找不到 Key,檢查 properties 文件內鍵名是否含隱形空格、大小寫不一致。

最佳實踐

  • 統一在 applicationContext.xml 用 context:property-placeholder 載入 classpath*: 多路徑。
  • 子容器(Servlet)僅掃描 Controller,不重複定義 PropertyPlaceholderConfigurer。
  • 外部化配置優先級:file:/conf/ > classpath*: > JAR 內部,避免版本衝突。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved