SpringBootで特定の設定ファイルを読み込む方法は?

Spring Bootでは、@ConfigurationPropertiesアノテーションを使用して特定の設定ファイルを読み込むことができます。具体的な手順は以下の通りです。

  1. プロジェクトのresourcesディレクトリに、例えばapplication-dev.propertiesという設定ファイルを作成してください。ここで、devは環境名を指定するものです。
  2. Spring Bootプロジェクトの設定クラスに@ConfigurationPropertiesアノテーションを追加し、prefixプロパティを設定ファイル内の接頭辞に設定します。例えば、「spring.datasource」です。同時に、locationsプロパティを設定ファイルのパスに設定し、例えば、「classpath:application-${spring.profiles.active}.properties」とします。

以下はサンプルコードです。

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
@PropertySource(value = {"classpath:application-${spring.profiles.active}.properties"})
public class DataSourceConfig {
    private String url;
    private String username;
    private String password;

    // getters and setters
}
  1. pom.xmlファイルに以下の依存関係を追加してください。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
  1. application.propertiesまたはapplication.ymlファイルで、”spring.profiles.active”プロパティを特定の環境に設定します。例えば、”dev”です。
spring.profiles.active=dev

もしくは

spring:
  profiles:
    active: dev

このようにすると、Spring Bootは指定された設定ファイルに基づいて対応する設定情報を読み込みます。

bannerAds