简体   繁体   English

Spring 启动:在运行时创建配置属性 bean

[英]Spring boot: create configuration properties bean in runtime

Is there a way to create @ConfigurationProperties beans in runtime using spring's functionality?有没有办法使用spring的功能在运行时创建@ConfigurationProperties bean? 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.假设我想 state 自定义注释中的前缀并在运行时为它们创建 bean,因为手动创建它们对我来说似乎是样板。

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.然后在运行时,我希望从具有这些前缀的属性创建两个指定类型的配置 bean。 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?我知道我可以使用注释处理器为它们生成代码,但也许通过 spring 的 bean 处理器或类似的东西更容易实现?

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. 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. https://www.baeldung.com/spring-annotation-bean-pre-processor博客将有助于了解它如何与注释处理器一起使用。

(Here)[ Spring: access all Environment properties as a Map or Properties object you can see how to get map of properties. (在这里)[ Spring:以 Map 或属性 object 的形式访问所有环境属性,您可以查看如何获取 Z1D78DC8ED541214E9AEZEB 的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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