Skip to content
Advertisement

Spring Boot – Dynamically creating prototype Beans using properties

Is it possible to create prototype beans using some pattern in @Value annotation with properties / yaml configuration?

There is an example what I mean:
Example object:

JavaScript

Example properties:

JavaScript

I need to create two prototype beans
first with key “first”
second with key “second”
Ideal – if they will initialized like singletons on startup application

Advertisement

Answer

Yes you want to use Configuration Properties to allow binding of custom properties to a POJO.

JavaScript

And enable add @EnableConfigurationProperties(MyProperties.class) to your main application or a @Configuration class.

AFter this you can inject the MyProperties to any Spring bean and use it as any other java object.

For example,

JavaScript

Will print each of the items.

Working example can be found here,

https://github.com/DarrenForsythe/configuration-properties-example

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement