'SpringBoot 2.6.3 not binding @ConfigurationProperties on List of Objects
I know this must be simple, and I've seen multiple similar questions, however my entire setup seems to be ok (as solutioned in the other posts), yet this problem persists.
Here's my setup
Environment
- Spring Boot
2.6.3
- Java
17
application.yml
platforms:
configs:
- platform: ABC
base-url: https://some-url-01.com/api
description:
logo:
- platform: DEF
base-url: https://some-url-02.com/api
description:
logo:
Config Properties
@Data
@ConstructorBinding
@ConfigurationProperties(prefix = "platforms")
public class PlatformProperties {
private final List<PlatformConfig> configs = new ArrayList<>();
@Data
public static class PlatformConfig {
private final Platform platform;
private final String baseUrl;
private final String description;
private final String logo;
}
}
Platform.java - a simple enum
public enum Platform {
ABC, DEF
}
Configuration
@Slf4j
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(PlatformProperties.class)
public class ClientConfig {
private final PlatformProperties platformProperties;
@PostConstruct
public void showProperties(){
platformProperties.getConfigs().forEach(System.out::println);
}
}
This entire setup seems perfectly fine (Ref: Spring Docs), however platformProperties.getConfigs()
is always empty because there was no binding on platforms.configs
as defined from the application.yml
I have a similar setup on a different project (springboot 2.5.7
/ Java 8
) where everything works exactly as expected.
What about this setup/configs is wrong???
Solution 1:[1]
Yah, I solved this a long time ago, just wanted to provide the answer, and it was quite simple too.
You see this line?
private final List<PlatformConfig> configs = new ArrayList<>();
That was the culprit.
Notice that the configs
variable is final and was already assigned a new ArrayList<>()
as it's value, hence it was immutable.
Solution was to remove the initial assignment so the line became;
private final List<PlatformConfig> configs;
The constructor binding went OK and the configs
values were populated as expected.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SourceVisor |