1. 程式人生 > 其它 >SpringBoot下讀取自定義properties配置檔案

SpringBoot下讀取自定義properties配置檔案

SpringBoot工程預設讀取application.properties配置檔案。如果需要自定義properties檔案,如何讀取呢?

一、在resource中新建.properties檔案

在resource目錄下新建一個config資料夾,然後新建一個.properties檔案放在該資料夾下。如圖remote.properties所示

二、編寫配置檔案

remote.uploadFilesUrl=/resource/files/ 
remote.uploadPicUrl=/resource/pic/

三、新建一個配置類RemoteProperties.java

@Configuration
@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
@PropertySource("classpath:config/remote.properties")
@Data
@Component
public class RemoteProperties {
private String uploadFilesUrl;
private String uploadPicUrl;
}

其中
@Configuration 表明這是一個配置類
@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false) 該註解用於繫結屬性。prefix用來選擇屬性的字首,也就是在remote.properties檔案中的“remote”,ignoreUnknownFields是用來告訴SpringBoot在有屬性不能匹配到宣告的域時丟擲異常。
@PropertySource("classpath:config/remote.properties") 配置檔案路徑
@Data 這個是一個lombok註解,用於生成getter&setter方法,詳情請查閱lombok相關資料
@Component 標識為Bean

四、如何使用?
在想要使用配置檔案的方法所在類上表上註解
EnableConfigurationProperties(RemoteProperties.class)

並自動注入

@Autowired

RemoteProperties remoteProperties;

在方法中使用remoteProperties.getUploadFilesUrl()就可以拿到配置內容了。

@EnableConfigurationProperties(RemoteProperties.class)
@RestController
public class TestService{
    @Autowired
    RemoteProperties remoteProperties;

    public void test(){
        String str = remoteProperties.getUploadFilesUrl();
        System.out.println(str);
    }
}

  

這裡str就是配置檔案中的”/resource/files/”了。