【发布时间】:2019-06-20 17:50:10
【问题描述】:
我注意到启动期间使用的某些属性只能在application.properties 中设置。
例如:
src/main/java/foo/bar/Foo.java
@SpringBootApplication
public class Foo {
private static final Logger log = LoggerFactory.getLogger(Foo.class);
public static void main(String... args) {
ApplicationContext appContext = SpringApplication.run(Foo.class, args);
log.info(appContext.getEnvironment().getProperty("spring.profiles.active"));
}
}
src/main/resources/application.properties
spring.profiles.active=dev
控制台日志:
09:23:48.827 : The following profiles are active: dev
09:23:50.832 : dev
配置文件在启动时被识别为dev,并在Environment 中可用。这是预期的行为。
但是,如果我将同一属性从 application.properties 移动到 foo.properties 并将其加载为 @PropertySource,则行为会发生变化。
src/main/java/foo/bar/FooConfiguration.java
@Configuration
@PropertySource("classpath:foo.properties")
public class FooConfiguration { }
src/main/resources/foo.properties
spring.profiles.active=prod
src/main/resources/application.properties
# empty
控制台日志:
09:35:18.141 : No active profile set, falling back to default profiles: default
09:35:20.175 : prod
在启动期间不考虑配置文件,但在启动后在Environment 上可用。
问题:我如何从@PropertySource 加载属性,并在启动时同时加载其余的application.properties?
【问题讨论】:
-
我认为
@propertySource是特定于类或 bean 的Given a file app.properties containing the key/value pair testbean.name=myTestBean, the following @Configuration class uses @PropertySource to contribute app.properties to the Environment's set of PropertySources. -
好的,那你为什么不尝试在主类上添加这个
PropertySource("classpath:foo.properties")并尝试一下? -
@Zack,你有没有在你的 application.properties 中尝试过这个:spring.config.location=file:foo.properties 或 classpath:foo.properties?
-
@Zack 好吧,那是我的疯狂猜测。没关系。我也删除了它,因为其他偶然发现它的人可能会感到困惑,因此您已确认它不起作用,我必须删除该评论。
-
这可能会提供更多信息stackoverflow.com/questions/43020491/…
标签: java spring spring-boot properties-file