yml文件中的属性值未加载到springboot项目中的类中

时间:2018-05-02 19:43:50

标签: java spring-boot yaml

请在application.yml

中找到以下代码
decrypt: /Users/Blahblah/Bleh

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

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

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

2 个答案:

答案 0 :(得分:0)

首先,application.yml应位于src/main/resources/application.yml

之下

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

public class PropertyLoader implements InitializingBean{

    private String decryptPath;

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

     }
    }   

答案 1 :(得分:0)

事实证明,由于这个类正在实现InitializingBean,因此在该类完成执行之前,属性对象不会被初始化。 @Value将始终返回null。

相关问题