从app.properties中获取值,并使用@Value Springboot将其存储在变量中。

问题描述 投票:0回答:1

我想访问存储在Spring Boot App的application.properties中的变量值,使用下面的代码,我可以访问变量中的值。

应用程序.属性

path.animals=topcatwhite

编码

import org.springframework.beans.factory.annotation.Value;

    @Value("${path.animals}")
    private String FOLDER_PATH;
    private String absolute_folder_path = "/home/johnDoe/Documents/" + FOLDER_PATH;

当我把这两个变量打印在屏幕上时,我得到的是

FOLDER_PATH : topcatwhite

绝对文件夹路径 :homejohnDoeDocumentsnull。

我需要 absolute_folder_path 应是 /home/johnDoe/Documents/top/cat/white.

注意:这两个变量都是在方法外部声明的。这两个变量都是全局变量

java spring-boot spring-annotations
1个回答
2
投票

发生这个问题是因为absolute_folder_path还没有得到文件夹路径的值。而这是因为Spring注入这些值的方式。你想在哪里打印它们?

你可以尝试使用构造函数进行自动布线,并在构造函数中设置absolute_folder_path的值。

例子

public class Test{

    private String FOLDER_PATH;
    private String absolute_folder_path;

@Autowired
  public Test(@Value("${path.animals}") String folderPath){
    FOLDER_PATH= folderPath;
    absolute_folder_path = "/home/johnDoe/Documents/" + folderPath;
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.