spring-projects / spring-projects/spring-boot
Cannot initialize a map inside @ConfigurationProperties
Open
Nobody has claimed this yet.
status: pending-design-work
type: enhancement
- Dominant language
- Java
- Stars
- 81.5k
- Forks
- 42.7k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 65
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Use the supplied SpringBootTest reproduction and start at the @ConfigurationProperties binding of Bar.foos. Investigate why binding the map replaces the initialized Foo value's name, then verify the behavior against the shown assertions. Done means initialized values such as Bob's name are preserved while configured map properties still bind correctly.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java, spring-boot
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100