4

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.

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
B-ron
  • 181
  • 2
  • 5
  • 1
    If you use a Bean-annotated method, then *you* create and return the bean instance, so *you* invoke its constructor, so I don't see how Spring could invoke it. You would need something like `@Bean @ConfigurationProperties("foo.baz") @ConstructorBinding public MyBean myBean1(String prop1, String prop2) { return new MyBean(prop1, prop2); }`, but then the annotation name (ConstructorBinding) would be inappropriate. I don't think there is any support for that. I would probably just define two subclasses of the same base class and annotate those subclasses. – JB Nizet Nov 20 '19 at 00:01
  • Yeah, I think there are various workarounds but I was hoping there would be direct support for multiple instances the way that non constructor-bound beans could. It would be kind of a pain to have to statically create a subclass for multiple (identical) config classes. – B-ron Nov 21 '19 at 18:03

1 Answers1

3

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

Mister_Jesus
  • 194
  • 1
  • 12