Skip to content

Cannot initialize a map inside @ConfigurationProperties #43352

Open
@dsyer

Description

@dsyer

This fails

@SpringBootTest(properties = { "bar.foos.alice.name=alice", "bar.foos.alice.age=20",
        "bar.foos.bob.age=21" }, classes = PropertiesTests.Bar.class)
public class PropertiesTests {

    @Autowired
    private Bar bar;

    @Test
    public void test() {
        assertThat(bar.getFoos().get("alice").getAge()).isEqualTo(20);
        assertThat(bar.getFoos().get("alice").getName()).isEqualTo("alice");
        assertThat(bar.getFoos().get("bob").getAge()).isEqualTo(21);
        assertThat(bar.getFoos().get("bob").getName()).isEqualTo("bob");
    }

    @TestConfiguration
    @ConfigurationProperties("bar")
    static class Bar {
        private Map<String, Foo> foos = new HashMap<>(Map.of("bob", new Foo("bob")));

        public Map<String, Foo> getFoos() {
            return foos;
        }
    }

    static class Foo {
        private String name;
        private int age;

        Foo() {
        }

        public Foo(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

Bob’s name is null.

It means you can't initialize a map if you are going to bind to it as well (there's no point as it will just get overwritten). That seems like a bug to me.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions