How do I express a list or array of objects in yaml via a Spring placeholder?

Viewed 4770

I know that you can override yaml config values with placeholders like so:

some-setting: ${SOME_SETTING:default value}

And I know that you can express lists of objects like so:

customers:
  - name: acme
    category: manufacturing
    employees: 200 
  - name: virtucon
    category: evil
    employees: 1

So how would I express such a list via the ${} placeholder notation?

1 Answers

You would have to create a ConfigurationProperties to read in the property objects.

@Component
@ConfigurationProperties("app")
public class AppProperties {

    private List<Customer> customers = new ArrayList<>();

    public static class Customer {
        private String name;
        private String category;
        private int employees;
    }
}

Usually you would also create a prefix for this in your .yml file also

app:
   customers:
   - name: acme
     category: manufacturing
     employees: 200
   - name: virtucon
     category: evil
     employees: 1 

You can now auto-wire this class anywhere in your application.

Related