对多个 Bean 使用 Spring Boot 2.2.0 的 @ConstructorBinding [英] Using Spring Boot 2.2.0's @ConstructorBinding for multiple Beans

查看:28
本文介绍了对多个 Bean 使用 Spring Boot 2.2.0 的 @ConstructorBinding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我对新的 @ConstructorBinding 功能感到非常兴奋,但我有一个关于它如何与 @ConfigurationProperties 交互的问题.可以通过更改前缀来声明具有配置属性的多个相同类型的 bean,例如:

So I'm very excited about the new @ConstructorBinding feature but I have a question about how it interacts with @ConfigurationProperties. It is possible to declare multiple beans of the same type with configuration properties by changing the prefix, e.g.:

    @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.

这是预期支持的内容吗?它是否已经支持并且我已经错过了什么?我想我理论上可以将构造函数绑定的类包装在另一种类型中,但它似乎有点hack-ish,如果可能的话,我宁愿避免它.

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.

推荐答案

正如评论中所说,没有任何机制可以创建 @ConfigurationProperties 组件的多个实例.我发现 @ConstructorBinding 只有一种解决方法 - 对于类似的属性,我创建了不同的类,这些类继承了基本属性类并定义了自己的构造函数.我认为创建一个简单的类和构造函数不需要太多的工作时间(特别是如果你使用 IDE).

As said in comments, there is not any mechanism to create multiple instances of @ConfigurationProperties component. I found only one workaround for @ConstructorBinding- for similar properties i create different classes which inherit the base properties class and define own constructor. I think creating a simple class and constructor doesn't take too much work time (especially if you work with IDE).

这篇关于对多个 Bean 使用 Spring Boot 2.2.0 的 @ConstructorBinding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆