Spring Bootが設定ファイルをロードする方法

Spring Bootは@PropertySourceアノテーションによってコンフィグレーションファイルを読み込む。

  1. @SpringBootアプリケーション
  2. @PropertySource
  3. application.properties
@SpringBootApplication
@PropertySource("classpath:application.properties")
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
  1. application.properties
server.port=8080
  1. @Valueでネイティブに言い換えてください。
  2. @Component
  3. サーバーポート
@Component
public class MyComponent {
    @Value("${server.port}")
    private String port;
    
    // ...
}

Spring Bootによる設定ファイルの読み込み方法は上記のようなものとなります。設定ファイルには必要な設定項目を追加し、必要な箇所でアノテーションを介して設定項目の値を利用します。

bannerAds