You have the following code
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
Products products = new Products(); <---------------------------------ERROR!!!
List<String> productsFromApplicationYml = products.getProducts();
System.out.println(productsFromApplicationYml.size()); // I would like to see 2
products.getProducts().forEach(System.out::println); // I would like to see "first" and "second"
}
@Component
@ConfigurationProperties(prefix="products")
public class Products {
private final List<String> products = new ArrayList<>();
public List<String> getProducts() {
return products;
}
}
The error is in the line Products products = new Products(); of your main method. You don't retrieve the bean from Spring context but you create it by yourself in the JVM. Therefore it is as you created it empty.
Read more to understand how Spring uses proxies for your spring beans and not the actual classes that you write.
What you need is the following
public static void main(String[] args) {
ApplicationContext app = SpringApplication.run(Demo1Application.class, args)
Products products = app.getBean(Products.class); <---Retrieve the Proxy instance from Spring Context
List<String> productsFromApplicationYml = products.getProducts();
System.out.println(productsFromApplicationYml.size())
Edit:
You have also false configured your application.yml file.
products:
- first
- second
The symbol - is used for array of complex objects which spring will try to serialize from application.yml. Check what I mean in this SO thread
Considering that you don't have a list of custom objects but a primitive List<String> your application.yml should be in the following form
products: first,second