@value无法从springboot中的application.properties读取

时间:2018-04-16 18:38:03

标签: spring spring-boot

我正在尝试使用@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);
}
}

P.S。 registry.system.base位于application.yml中。

1 个答案:

答案 0 :(得分:1)

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

相关问题