【问题标题】:Property values in yml file not loading into a class in springboot projectyaml文件中的属性值未加载到spring boot项目中的类中
【发布时间】:2018-10-13 00:30:02
【问题描述】:

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

decrypt: /Users/Blahblah/Bleh

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

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

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

【问题讨论】:

  • application.yml 是在 src/main/resources 文件夹还是其他地方
  • 你能粘贴完整的 application.yml 吗?
  • @sumitsingh 一切都正确缩进。

标签: java spring-boot yaml


【解决方案1】:

首先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;

     }
    }   

【讨论】:

  • 好吧,你能试试@PostContruct
  • @PostConstruct public void initIt() { }
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-18
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    相关资源
    最近更新 更多