首页 > 解决方案 > 来自 Bean 方法的 Immutabel ConfigurationProperties

问题描述

您可以通过ConfigurationProperties多种方式使用 Spring 创建 -Objects。

一种方法是将@ConfigurationProperties-Annotation添加到 -Declaration 中,@Bean如下所示:

@Bean
@ConfigurationProperties("my.property.group")
public MyProperties myProperties() {
   return new MyProperties();
}

它将从MyProperties-class 创建一个 bean,然后使用它的setter来用配置文件中的值填充其成员。

您也可以直接在MyProperties-Object 上添加注释,如下所示:

@ConfigurationProperties("my.property.group")
public class MyProperties {
    @Getter @Setter private String myFirstValue;
    @Getter @Setter private String mySecondValue;
}

通过放置@EnableConfigurationProperties(MyProperties.class)到任何加载的配置来创建它。

也可以以不可变的方式创建此类,使用@ConstructorBinding

 @ConfigurationProperties("my.property.group")
 @ConstructorBinding
 public class MyProperties {
     @Getter private final String myFirstValue;
     @Getter private final String mySecondValue;
     
     public MyProperties(String myFirstValue, String mySecondValue) {
         this.myFirstValue = myFirstValue;
         this.mySecondValue = mySecondValue;
     }
 }

但是如何结合第一个 @Bean 方法创建不可变的 ConfigurationProperties?

我试过这样的事情:

 @Bean
 @ConfigurationProperties("my.property.group")
 // @ConstructorBinding <---- This is not applicable to methods
 public MyProperties myProperties(String myFirstValue, String mySecondValue) {
     return new MyProperties(myFirstValue, mySecondValue);
 }

这告诉我,它无法自动装配参数,我将考虑声明一些类型的 beanString

标签: javaspring

解决方案


在它的Spring Boot参考文档@ConstructorBinding中说:

要使用构造函数绑定,必须使用 @EnableConfigurationProperties 或配置属性扫描启用该类。您不能对由常规 Spring 机制创建的 bean 使用构造函数绑定(例如,@Component bean、通过 @Bean 方法创建的 bean 或使用 @Import 加载的 bean)

可以在此处找到 Spring Boot 文档。

也许这里的一些答案足以解决您的问题。


推荐阅读