我想(如果可能)使用@ConfigurationProperties创建POJO的动态大小列表。请告知是否可行。我的想法如下(省略了无参数构造函数/ getter / setter):

属性文件:

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

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


以及应该填充的bean:

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

    private List<Item> items;

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


不幸的是,当我@Autowire ItemsConfig时,列表始终是null

@ConfigurationProeprties是否可以实现类似的目的?

我找到了一种解决方法,可通过BeanFactoryPostProcessor遍历属性并手动创建所有内容,并使用其可怕的代码:(

请指教

PS:我确实在@EnableConfigurationProperties上使用了@Configuration

注意:一旦解决,我可能会发现人们很有用,必须意识到在使用spring创建具有@EnableConfigurationProperties的组件之前必须找到并处理@ConfigurationProperties注释。否则,将不会填充Bean。

最佳答案

属性条目存在一个小问题,应该是以下情况:

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

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


注意itemsitem,以匹配设置器名称

09-30 17:50
查看更多