简体   繁体   English

对多个 Bean 使用 Spring 引导 2.2.0 的 @ConstructorBinding

[英]Using Spring Boot 2.2.0's @ConstructorBinding for multiple Beans

So I'm very excited about the new @ConstructorBinding feature but I have a question about how it interacts with @ConfigurationProperties .所以我对新的@ConstructorBinding功能感到非常兴奋,但我有一个关于它如何与@ConfigurationProperties交互的问题。 It is possible to declare multiple beans of the same type with configuration properties by changing the prefix, eg:可以通过更改前缀来声明具有配置属性的多个相同类型的bean,例如:

    @Bean("myBean1")
    @ConfigurationProperties("foo.baz")
    MyBean myBean1(){
        return new MyBean();
    }

    @Bean("myBean2")
    @ConfigurationProperties("foo.bar")
    MyBean myBean2(){
        return new MyBean();
    }

But as far as I can tell from the documentation, the constructor binding approach requires you to directly annotate the type, which (I believe) necessarily precludes you from having multiple instances of one class injected with configuration properties.但是据我从文档中可以看出,构造函数绑定方法要求您直接注释类型,这(我相信)必然会阻止您将一个 class 的多个实例注入配置属性。

Is this something that is expected to be supported?这是期望得到支持的东西吗? Is it already supported and I'm already missing something?它是否已经受支持并且我已经遗漏了一些东西? I figure I could theoretically wrap the constructor-bound classes in another type but it seems a little hack-ish and I'd rather avoid it if possible.我想我理论上可以将构造函数绑定的类包装在另一种类型中,但它似乎有点hack-ish,如果可能的话我宁愿避免它。

As said in comments, there is not any mechanism to create multiple instances of @ConfigurationProperties component.正如评论中所说,没有任何机制可以创建@ConfigurationProperties组件的多个实例。 I found only one workaround for @ConstructorBinding - for similar properties i create different classes which inherit the base properties class and define own constructor.我只找到了@ConstructorBinding的一种解决方法——对于类似的属性,我创建了不同的类,这些类继承了基本属性 class 并定义了自己的构造函数。 I think creating a simple class and constructor doesn't take too much work time (especially if you work with IDE).我认为创建一个简单的 class 和构造函数不会花费太多工作时间(特别是如果您使用 IDE)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM