Springbootはどのように構成ファイルを読み込みますか?

Spring Boot では、@Value アノテーション、Environment インタフェース、@ConfigurationProperties アノテーションといった方法で設定ファイルを読み込むことができる。

  1. @Value
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {

    @Value("${my.property}")
    private String myProperty;
    
    // ...

    public void doSomething() {
        System.out.println(myProperty);
    }
}

上記のコードでは、@Value(“${my.property}”)アノテーションは構成ファイルのmy.propertyの値をmyPropertyプロパティに挿入するために使われます。

  1. 環境
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {

    @Autowired
    private Environment env;
    
    // ...

    public void doSomething() {
        String myProperty = env.getProperty("my.property");
        System.out.println(myProperty);
    }
}

env.getProperty(“my.property”)メソッドにより設定ファイル中のmy.propertyの値を取得

  1. @ConfigurationProperties
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {

    private String property;

    // ...

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }
}

@ConfigurationProperties(prefix = “my”)は、プレフィックスがmyの設定プロパティの値を、同じ名前のプロパティに注入します。 application.propertiesの設定ファイルで、propertyプロパティの値はmy.propertyを通じて設定できます。

@ConfigurationPropertiesアノテーションを使用する場合、設定プロパティのインジェクションを有効にするためにメインクラスで@EnableConfigurationProperties(MyProperties.class)アノテーションを追加する必要があります。

これらの方法に加えて、@PropertySourceアノテーションや@Configurationアノテーションなどを利用して、設定ファイルをロードすることもできます。どの方法を使用するかは、あなたのニーズや個人的な好みに依存します。

bannerAds