Springbootで外部ファイルを読み込む方法
Spring Bootでは、外部ファイルを読み取る方法は多数用意されています。以下はそのうちによく使われる方法です。
- ネイティブで日本語に言い換えておきます。ただし、1 つだけオプションが必要です。: @Value
- ネイティブに
- application.properties
- my.file.path=/path/to/file.txt
- @Value
@Value("${my.file.path}")
private String filePath;
- 環境
- 環境
- 環境
- プロパティを取得()
@Autowired
private Environment env;
public void readFilePath() {
String filePath = env.getProperty("my.file.path");
}
- ネイティブに構成プロパティ
- @ConfigurationPropertiesを使用
- ConfigurationProperties
- 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();
}
上記の方法は一般的な使用例であり、実際のニーズに応じて適切な方法を選択して外部ファイルを読み取ることができます。