【问题标题】:Immutabel ConfigurationProperties from Bean Methods来自 Bean 方法的不可变配置属性
【发布时间】:2021-02-25 08:08:37
【问题描述】:

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

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

@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);
 }

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

【问题讨论】:

标签: java spring


【解决方案1】:

Spring Boot@ConstructorBinding 参考文档中说:

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

Spring boot 文档可以在here找到。

也许here的一些答案足以解决你的问题。

【讨论】:

  • 谢谢你,法提赫!到目前为止,我已经知道了,因为@ConstructorBinding@Target-List 中没有METHOD。考虑到这个名字,这也会很奇怪。我宁愿有一些@BeanMethodBinding 或类似的东西。通过@Bean-Methods 创建不可变@ConfigurationProperties 的任何干净方式。
  • @derM 也许here 的答案会对你想做的事情有所帮助。
猜你喜欢
  • 1970-01-01
  • 2013-01-31
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 2020-11-27
  • 1970-01-01
相关资源
最近更新 更多