Springbootで外部ファイルを読み込む方法

Spring Bootでは、外部ファイルを読み取る方法は多数用意されています。以下はそのうちによく使われる方法です。

  1. ネイティブで日本語に言い換えておきます。ただし、1 つだけオプションが必要です。: @Value
  2. ネイティブに
  3. application.properties
  4. my.file.path=/path/to/file.txt
  5. @Value
@Value("${my.file.path}")
private String filePath;
  1. 環境
  2. 環境
  3. 環境
  4. プロパティを取得()
@Autowired
private Environment env;
public void readFilePath() {
String filePath = env.getProperty("my.file.path");
}
  1. ネイティブに構成プロパティ
  2. @ConfigurationPropertiesを使用
  3. ConfigurationProperties
  4. application.properties
@ConfigurationProperties(prefix = "my.file")
public class FileProperties {
private String path;
// getter and setter
}
// application.properties
my.file.path=/path/to/file.txt
// Code
@Autowired
private FileProperties fileProperties;
public void readFilePath() {
String filePath = fileProperties.getPath();
}

上記の方法は一般的な使用例であり、実際のニーズに応じて適切な方法を選択して外部ファイルを読み取ることができます。

bannerAds