Using Spring Boot 2.2.0's @ConstructorBinding for multiple Beans

与世无争的帅哥 提交于 2021-01-27 22:42:54

问题


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.

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.


回答1:


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



来源:https://stackoverflow.com/questions/58944506/using-spring-boot-2-2-0s-constructorbinding-for-multiple-beans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!