作为 Spring Boot 项目的一部分,我试图在创建 Spring ApplicationContext 之前读取 application.properties,如下所示,
主类
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurationClass con = new ConfigurationClass();
con.readProperties();
ApplicationContext c = SpringApplication.run(DemoApplication.class, args);
}
}
配置类,
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@PropertySource("classpath:application.properties")
public class ConfigurationClass {
private String value1;
private String value2;
@Autowired
private Environment env;
public void readProperties() {
value1 = env.getProperty("app.value1");
value2 = env.getProperty("app.value2");
}
public String getValue1() {
return value1;
}
public String getValue2() {
return value2;
}
}
我想从 application.properties 中获取一些基本值并进行一些配置。这段代码发生的事情是它抛出一个nullpointerexceptionsince envis null during value1 = env.getProperty("app.value1");。
我在这里做错了什么?
在创建 springapplication 上下文之前的这个时间点,我如何读取 application.properties 中的值?
任何帮助,将不胜感激!
暮色呼如
相关分类