首页 > 解决方案 > yml 文件中的属性值未加载到 springboot 项目中的类中

问题描述

请在下面找到 application.yml 的代码

decrypt: /Users/Blahblah/Bleh

我们试图读入类的上述属性请找到 PropertyLoader.java 的代码

@Configuration
@Component
public class PropertyLoader implements InitializingBean{
    @Value("${decrypt}")
    private String decryptPath;
    <--->
}

值 decryptPath 始终为空。谁能告诉我代码有什么问题?

标签: javaspring-bootyaml

解决方案


首先 application.yml 应该在src/main/resources/application.yml.

如果你想在构造函数中使用这个变量,你不会。因为spring在构造之后注入@Value注释变量。但是如果你想在构造函数中做你可以这样做:

public class PropertyLoader implements InitializingBean{

    private String decryptPath;

    public PropertyLoader(@Value("${decrypt}") decrypPath) {
     this.decryptPath = decryptPath;

     }
    }   

推荐阅读