LoginSignup
0
0

More than 1 year has passed since last update.

Spring Boot設定ファイル読み込み

Posted at

設定ファイルに記述

Spring Bootではapplication.ymlやapplication.propertiesに設定項目を書き込んでいく。

server:
  port: 8080

api:
  host: [ホストのドメイン]
  port: 8080

読み込み

設定ファイルに項目を書き込んだ後には読み込みが必要。ここで@ConfigurationPropertiesアノテーションを使用することで、Config用のクラスから読み込み可能。通常はセッターでプロパティを設定する必要があるが、@ConstructorBindingを使用することで、コンストラクタで初期化時でプロパティを設定し、以降は変更しないようにできる。(セッターは不要)

@ConstructorBinding
@ConfigurationProperties(prefix = "api")
public class ApiConfiguration {
    private final String host;
    private final int port;

    public ApiConfiguration(String host, int port) {
        this.host = host;
        this.port = port;
    }

    // getterは略。実装は必要。
}

使用

実際の通信はDAOに任せるので、上の例ではDAOの実装クラスで使えれば良い。なので、DAOのプロパティにApiConfigurationを定義し、コンストラクタインジェクションを行えば良い。また、インジェクション後にゲッターでhostとportを取ってきて、urlを作成するにはInitializingBeanを実装しafterPropertiesSetをオーバーライドすれば問題なくいける。Apiが呼び出されるたびにhostとportをgetしてきてもいい気はするが、無駄を省くならインジェクション後に行うべきなのかもしれない。

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