Nikita Mikhailov
Nikita Mikhailov

Reputation: 516

Spring boot: create configuration properties bean in runtime

Is there a way to create @ConfigurationProperties beans in runtime using spring's functionality? Let's say I want to state the prefixes in my custom annotation and create beans for them in runtime because creating them manually seems like a boiler-plate to me.

Something like this:

@MyAnnotation({
     @CustomProps(prefix="foo"),
     @CustomProps(prefix="bar")
})

And then in runtime, I want to have two config beans of the specified type created from properties with these prefixes. I know I can generate code for them using an annotation processor, but maybe it's easier to achieve by spring's bean processors or something like this?

Upvotes: 1

Views: 1600

Answers (1)

Vinay Prajapati
Vinay Prajapati

Reputation: 7505

Yes! you can achieve it but you can't have class fields for each property. So, easy approach is use spring annotation processor and for fields you can use map which you could map using Environment bean.

https://www.baeldung.com/spring-annotation-bean-pre-processor blog would be helpful in understanding how it works with annotation processor.

(Here)[Spring: access all Environment properties as a Map or Properties object you can see how to get map of properties.

Upvotes: 1

Related Questions