简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM