Spring Boot 应用程序在 main 方法中从属性文件中读取值

Cor*_*chi 5 spring spring-boot

我正在尝试获取财产的价值

hello.world=Hello World
Run Code Online (Sandbox Code Playgroud)

在 MainApp 类中

@SpringBootApplication
public class MainApp {
   public static void main(String[] args) {
      SpringApplication.run(MainApp.class, args);
}
Run Code Online (Sandbox Code Playgroud)

这不是它的主要方法。

@Value("${hello.world}")
public static String helloWorld;
Run Code Online (Sandbox Code Playgroud)

也许它可以加载

  Properties prop = new Properties();

    // load a properties file
    prop.load(new FileInputStream(filePath));
Run Code Online (Sandbox Code Playgroud)

在 SpringApplication.run 之前的 SpringBoot 的 main 方法中,有没有其他更好的方法来使用 Spring 获取属性

san*_*nit 8

ConfigurableApplicationContext ctx = 
           SpringApplication.run(MainApp.class, args);
String str = ctx.getEnvironment().getProperty("some.prop");
System.out.println("=>>>> " + str);
Run Code Online (Sandbox Code Playgroud)

  • 当我们调用 `SpringApplication.run()` 时,它会启动诸如自动装配依赖等任务。在此之前,在 spring 的帮助下我们无法获取任何属性,要实现这一点,您必须手动读取属性文件。您能否在“run()”调用方法之前指定要读取属性的用例是什么? (2认同)