2017-09-04 103 views
1

我想使用application.properties文件中的值,以便將它傳遞給另一個類中的方法。問題是該值始終返回NULL。可能是什麼問題呢?提前致謝。Spring Boot:@Value總是返回null

application.properties

filesystem.directory=temp 

FileSystem.java

@Value("${filesystem.directory}") 
private static String directory; 

回答

5

不能在靜態變量使用@Value。你必須要麼將其標記爲不可靜態或者看看這裏的一個辦法值注入靜態變量:

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

編輯:萬一在未來的鏈接斷開。您可以通過非靜態的setter您靜態變量做到這一點:

@Component 
public class MyComponent { 

    private static String directory; 

    @Value("${filesystem.directory}") 
    public void setDirectory(String value) { 
     this.directory = value; 
    } 
} 

類需要雖然是一個Spring bean,否則它將不會被實例化和setter方法將被Spring無法訪問。

+0

感謝您的答覆,但它仍然打印空值。 –

+0

@JonathanWilliams是Spring bean中的成員變量? 「@ Value」註釋只適用於Spring bean,不適用於任何其他Java類。 – Jesper

+0

我做了一些編輯。你的班是Spring bean嗎?即它是用@Component註釋的嗎? – Plog

2

除了@ Plog的回答之外,還有幾件事情可以與你交叉檢查。

static變量不能被賦值。檢查@ Plog的答案。

  • 確保類與@Component@Service
  • 組件掃描註釋應該掃描封閉包註冊豆。如果啓用xml配置,請檢查您的XML。
  • 檢查屬性文件的路徑是否正確或在類路徑中。