LoginSignup
0
0
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

Spring Bootで設定ファイルを外部化したいし、設定値を再起動なしで変更したい

Last updated at Posted at 2024-06-15

要件

  • properties形式のファイルをclasspassの外、サーバ内の任意の場所に保持したい
  • ファイルの内容書き換え時のプログラムでの再読み込みを再起動なしで実現したい

実装

外部ファイルのパスをapplication.propertiesに書いておいて、そのパスにプログラム内でアクセスする仕組み。

private final ResourceLoader resourceLoader;

public class readingFile(){
    //1.設定ファイルオープン,2.読み込み
    Properties propertiesFile = this.getSettingFile();
    //3.設定値読み込み
    String value1 = propertiesFile.getProperty("example.value.first");
    //4.他クラスでプロパティファイル設定値を使いたい時はこのクラスから引き渡す
    Util.somethingUtility(value1,propertiesFile);
    
}

private Properties getSettingFile() {
    //1.ファイルオープン
    Resource resource = resourceLoader.getResource(settingFileLocation);
    Properties props = null;

    try {
        //2.設定ファイル読み込み
        props = PropertiesLoaderUtils.loadProperties(resource);
    } catch (IOException ioException) {
        log.error("Failed to load settings file.", ioException);
    }
    return props;
}

コード内のコメントに付けた番号と紐付けて説明します。

  1. SpringFrameworkのResourceクラスとResourceLoaderクラスを利用してファイルオープンと読み込みを行う
  2. 読み込んだ内容はjava.util.Propertiesクラスのオブジェクトに保持する
    PropertiesクラスではKey-Value(キー=値)形式の内容を扱うことができる
  3. Propertiesオブジェクトから値を取得するときは、PropertiesクラスのgetProperty(key)を利用する
  4. 別のクラスでもファイルを利用したい場合、別クラスで再度ファイル読み込みを行うのではなく、このクラスで読み込んだPropertiesオブジェクトを呼び出し先に引き渡す

application.propertiesはclasspath内に配置する必要があります。
正確には、java -jarコマンドでクラスパス指定すれば外部化は可能ですが、application.propertiesの内容の動的変更はどちらにしろ不可能です。

また、読み込みたいpropertiesファイルのパスを記述する際は、記法に注意してください。
クラスパス内に配置した場合は、クラスパスまではclasspath:で省略できます。

記載例:クラスパス内に配置した場合
app.settingfilelocation=classpath:example.properties

クラスパスの外に置いた場合は、フルパスの記述と、先頭にfile:///を書くことが必要です。

記載例:サーバ内の任意の場所に配置した場合
app.settingfilelocation=file:///C:/work/app/ext/example.properties

更に実現したい事

fileスキームでファイルパスを指定する際、アプリのルートからの相対パスで書きたい。

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0