Yaml 属性未在 spring boot 中加载

Yaml properties not loaded in springboot

我想使用 application.yml 而不是 application.properties

我关注了:https://docs.spring.io/spring-boot/docs/2.1.13.RELEASE/reference/html/boot-features-external-config.html

我正在使用:

我的 MCVE: https://github.com/OldEngineer1911/demo1

问题是:未加载属性。有人可以帮忙吗?

您有以下代码

@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;
    }
}

错误在您的 main 方法的 Products products = new Products(); 行。您不会从 Spring 上下文中检索 bean,而是您自己在 JVM 中创建它。因此,它就像您创建它时一样是空的。

阅读更多内容以了解 Spring 如何为您的 spring beans 而不是您编写的实际 类 使用代理。

您需要的是以下内容

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())

编辑:

您还错误地配置了 application.yml 文件。

products:
  - first
  - second

符号 - 用于复杂对象数组,spring 将尝试从 application.yml 序列化。检查我在

中的意思

考虑到您没有自定义对象列表,而是原始对象 List<String>,您的 application.yml 应该采用以下形式

products: first,second

“@Panagiotis Bougiokos”的解决方案部分正确:

Products products = app.getBean(Products.class); <---Retrieve the Proxy instance from Spring Context

是必须的,其余的是可选的(两种方式都可以在yml中写List)。解决方案是用嵌套产品修复 yml 文件:

products:
  products:
    - 'first'
    - 'second'

并为产品添加 setter:

@Component
@ConfigurationProperties(prefix="products")
public class Products {
    private List<String> products;

    public List<String> getProducts() {
        return products;
    }

    public void setProducts(List<String> products) {
        this.products = products;
    }
}

这是一个有效的解决方案(每个人都可以查看问题中提到的Github)。无论如何,它仍然可以改进 - 不知道为什么我需要嵌套产品。