Mapping a list of objects from application.yml with custom "root key" in Spring Boot

Viewed 433

I have setup the following configuration class for a Spring Boot application:

@Configuration
@ConfigurationProperties(prefix = "tasks")
@Getter
@Setter
public class TaskConfiguration {
    
    private List<TaskEntry> tasks;

    @Getter
    @Setter
    public static class TaskEntry {
        private String name;
        private String url;
        private String cronExpression;
    }
}

The application.yml defines the following values which can be read correctly in the application:

tasks:
    tasks:
    - name: A
      url: http://localhosta
      cronExpression: 1 2 3 4 5 A
    - name: B
      url: http://localhostb
      cronExpression: 1 2 3 4 5 B

However, you might have noticed that there is a duplicated tasks key in the configuration file. I couldn't find out yet how to get rid of it so that the YAML would look like this:

tasks:
    - name: A
      url: http://localhosta
      cronExpression: 1 2 3 4 5 A
    - name: B
      url: http://localhostb
      cronExpression: 1 2 3 4 5 B
1 Answers

From the ConfigurationProperties prefix is the prefix of the properties that are valid to bind to this object and in your case it means that tasks will be the prefix of all your configuration class properties including the tasks property that appears in your application.yml file. To avoid this situation you can use @ConfigurationProperties instead of @ConfigurationProperties(prefix = "tasks").

Related