SpringBoot讀取配置文件


目的是避免硬編碼。

使用場合一: controller 讀取配置文件(@Value)

  • 准備配置文件

  以 application.properties 為例。

web.images-path=D:\\IdeaProjects\\images
  • 在controller類加注解  

    @PropertySource("classpath:application.properties")

  • 在屬性上,加 @Value注解。

    @Value("${web.images-path}") private String filePath;
  • 然后在service里,使用 @Autowired注入。即可使用這些自定義的屬性值。

使用場合二: 通過實體類讀取配置文件

有配置文件如下

實體類和配置文件的key對應。

#測試配置文件注入
test.domain=www.xdclass.net
test.name=springboot

 

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Data
@Component
@PropertySource("classpath:application.properties")
public class ServerSettings {
    //名稱
    @Value("${test.name}")
    private String name;

    // 域名
    @Value("${test.domain}")
    private String domain;
}

 

另外 考慮 前綴取值的做法。

@ConfigurationProperties(prefix="test")

 

如果讀取配置文件失敗:

默認Spring框架實現會從聲明 @ComponentScan 所在的類的package進行掃描,來自動注入,因此啟動類最好放在根路徑下面,或者指定掃描包范圍。

 


免責聲明!

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



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