【问题标题】:@value not able to read from application.properties in springboot@value 无法从 spring boot 中的 application.properties 中读取
【发布时间】:2018-04-16 18:38:03
【问题描述】:

我正在尝试使用 @value 从属性文件中读取值,如下所示。

 @Value("${abc}")
private String abc;

  public List<Record> fetchRecords(String label, String predicate) {
   System.out.println(abc);

}

但 abc 的值为 null。而当我尝试使用@PostConstruct 打印相同的内容时,我得到了预期值。

@PostConstruct
    public void postconstruct() {
        System.out.println(abc);
    }

任何导致我无法在 fetchRecords() 方法中获取值的原因?

作为参考,这里是代码

@Component

public class AuditRecord {
    private String subject;
    private String predicate;
    private String oldObject;
    private String newObject;
    private String readOnlyAuthInfo;

    @Value("${registry.system.base}")
    private String registrySystemContext;

    public void record(DatabaseProvider provider) throws AuditFailedException {

        System.out.println("---registrySystemContext value showing null here---"+registrySystemContext);
       ...
     }
 @PostConstruct
    public void postconstruct() {
        System.out.println("---registrySystemContext value showing here as expected---"+registrySystemContext);
    }
}

我的调用方式如下:

@Component
public class RegistryDaoImpl implements RegistryDao {
...
private void addOrUpdateVertexAndEdge(Vertex v, Vertex dbVertex, GraphTraversalSource dbGraph, String methodOrigin){
...
    AuditRecord record = new AuditRecord();
                            record
                            .subject(dbVertex.label())
                            .predicate(e.label())
                            .oldObject(null)
                            .newObject(existingV.label())
                            .record(databaseProvider);
}
}

附: registry.system.base 在 application.yml 中。

【问题讨论】:

  • 您是否从正确的包中导入@Value?
  • @Tyler 我想是的
  • 您可能需要仔细检查您的导入。如果您的 IDE 自动导入其他一些 @Value,比如从 Lombok 导入,您可以预期会有一个空值。
  • 您的班级是否定义为@Component
  • 您是在 Spring 托管 bean 上调用该方法还是通过 new MyClass().fetchRecords() 调用该方法?发布一个完整的示例会很有帮助。

标签: spring spring-boot


【解决方案1】:

您需要自动连接AuditRecord,而不是直接使用new。只有这样,您才能在 Spring 的上下文中拥有您的课程。 我们不知道您对该类的确切用法,但您可能对 Spring 的 FactoryBean 感兴趣。

【讨论】:

    猜你喜欢
    • 2017-08-31
    • 2018-01-07
    • 2020-07-08
    • 2018-09-15
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多