1. 序章

このクイックチュートリアルでは、@ConfigurationPropertiesアノテーション付きクラスで@EnableConfigurationPropertiesアノテーションを使用する方法を示します。

2. @EnableConfigurationPropertiesアノテーションの目的

@EnableConfigurationPropertiesアノテーションは@ConfiguratonProperties。に厳密に接続されています

これにより、アプリケーションで@ConfigurationProperties注釈付きクラスのサポートが有効になります。 ただし、それを指摘する価値があります Spring Bootドキュメント言う、 すべてのプロジェクトには自動的に@EnableConfigurationPropertiesが含まれます。 したがって、 @ConfiguratonProperties サポートは、すべてのSpringBootアプリケーションで暗黙的にオンになっています。

プロジェクトで構成クラスを使用するには、それを通常のSpringBeanとして登録する必要があります。

まず、そのようなクラスに @Component。で注釈を付けることができます。あるいは、@Beanファクトリメソッドを使用することもできます。

ただし、特定の状況では、@ConfigurationPropertiesクラスを単純なPOJOとして保持することをお勧めします。 これは、@EnableConfigurationPropertiesが役立つ場合です。 このアノテーションですべての構成Beanを直接指定できます。

これは、@ConfigurationProperties注釈付きBeanをすばやく登録するための便利な方法です。

3. @EnableConfigurationPropertiesを使用する

それでは、実際に@EnableConfigurationPropertiesを使用する方法を見てみましょう。

まず、構成クラスの例を定義する必要があります。

@ConfigurationProperties(prefix = "additional")
public class AdditionalProperties {

    private String unit;
    private int max;

    // standard getters and setters
}

@ConfigurationPropertiesでのみAdditionalPropertiesに注釈を付けていることに注意してください。これはまだ単純なPOJOです。

最後に、@ EnableConfigurationPropertiesを使用して構成beanを登録しましょう。

@Configuration
@EnableConfigurationProperties(AdditionalProperties.class)
public class AdditionalConfiguration {
    
    @Autowired
    private AdditionalProperties additionalProperties;
    
    // make use of the bound properties
}

それで全部です! 他のSpringBeanと同じようにAdditionalPropertiesを使用できるようになりました。

4. 結論

このクイックチュートリアルでは、@ConfigurationProperties注釈付きクラスをSpringにすばやく登録する便利な方法を紹介しました。

いつものように、この記事で使用されているすべての例は、GitHubで入手できます。