简体   繁体   中英

Spring Boot and @ConfigurationProperties

I would like (if possible) to use @ConfigurationProperties to create dynamic sized list of POJOs. Please advice whether this is possible. My idea was something like follows (no-args constructors/getter/setters omitted):

The property file:

my.item[0].prop1=a
my.item[0].prop2=b

my.item[1].prop1=a
my.item[1].prop2=b

And the bean which should be populated:

@Component
@ConfigurationProperties(prefix = "my")
public class ItemsConfig {

    private List<Item> items;

    public static class Item {
        private String prop1;
        private String prop2;
    }
}

Unfortunatelly when I @Autowire the ItemsConfig the list is always null .

Can something similar be achieved with @ConfigurationProeprties ?

I found a workaround with BeanFactoryPostProcessor iterating over properties and creating everything manually bit its horrible code :(

Please advice

PS: I do use @EnableConfigurationProperties on my @Configuration

Note: Once resolved I though people may find useful to realize that the @EnableConfigurationProperties annotation must be found and processed before the component with @ConfigurationProperties is created by spring. Otherwise the bean won't be populated.

There is a small problem with the property entries, it should be the following:

my.items[0].prop1=a
my.items[0].prop2=b

my.items[1].prop1=a
my.items[1].prop2=b

Note the items vs item , to match the setter name

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