【发布时间】:2020-02-13 00:55:57
【问题描述】:
我正在尝试使用注释加载属性:
@PropertySource({"classpath:application.properties"})
和
@Value("${my.property}")
String myProperty;
因此,myProperty 始终为 null
在使用时:
BatchConfiguration.class.getClassLoader().getResourceAsStream("application.properties");
这是我的 Batch conf 类签名:
@Configuration
@ComponentScan
@EnableBatchProcessing
@PropertySource({"classpath:application.properties"})
public class BatchConfiguration {
@Value("${db.url}")
private String url;
...
}
和Application.java:
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
我也尝试使用以下方式加载它:
@Autowired
public static Environment env;
但是 env 也是空的。
【问题讨论】:
-
你能分享你的属性文件的位置吗?
-
Spring Boot 已经加载了
application.properties,无需手动尝试再次加载。你不能注入static变量。 -
我删除了
static和@PropertySource,仍然无法正常工作 -
你不需要
@PropertySource,因为 Spring Boot 已经加载了该文件。如果是null,那是因为您自己正在创建该类的实例。如果 Spring 会这样做,您的应用程序将无法启动,因为它无法解析属性。
标签: java spring spring-boot spring-batch