解決springboot項目中@Value注解參數值為null的問題


1、錯誤場景:

springboot項目中在.properties文件(.yml)文件中配置了屬性值,在Bean中使用@Value注解引入該屬性,Bean的構造器中使用該屬性進行初始化,此時有可能會出現屬性值為null,造成初始化程序的錯誤

2、錯誤原因:

因為Bean的構造器調用是在@Value屬性賦值之前進行的,所以造成了屬性還沒有賦值,就被調用的情況。

3、解決方案:

將構造器中需要使用的@Value屬性作為構造器的參數,確保構造器中使用該屬性之前,屬性已經得到初始化

理論先行,代碼跟上(^_^)

(1).yml配置文件中配置系統參數值 file.upload-dir

file:
  upload-dir: /Users/lc/temp/

(2)FileStorageService 的構造器需要使用使用 file.upload-dir 屬性

@Service
public class FileStorageService {
  /* @Value("${file.upload-dir}")
    private String uploadDir; */
public FileStorageService(@Value("${file.upload-dir}") String uploadDir) throws ServiceException { this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize(); try { Files.createDirectories(this.fileStorageLocation); } catch (Exception e) { throw new Exception(e); } } }

(3)now,問題解決了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM