问题
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