我在一个spring应用程序的资源目录中有2-3个.yml文件。我希望在应用程序启动时自动加载所有这些文件。
我尝试了下面的代码,但没有工作。
ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(YamlLoadApplication.class)
.properties("spring.config.name:applicationTest,CountriesData",
"spring.config.location:src/main/resources/")
.build().run(args);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
MutablePropertySources sources = environment.getPropertySources();请帮我解决这个问题。实现这一目标的最佳方法是什么?我将在整个应用程序中使用所有这些yml文件值。
谢谢
发布于 2018-09-18 08:38:52
这里有一个问题,"spring.config.location:src/main/resources/"将spring.config.location设置为src/main/resources/,它不是类路径资源,而是文件系统资源。这是从运行Spring应用程序的当前目录中查找的。
几个解决办法:
指定如下所示的完整文件系统路径:
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext;
applicationContext = new SpringApplicationBuilder(YmlsApplication.class)
.properties("spring.config.name:applicationTest,CountriesData",
"spring.config.location:/Users/msimons/tmp/configs/")
.build().run(args);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
MutablePropertySources sources = environment.getPropertySources();
sources.forEach(p -> System.out.println(p.getName()));
}或指定类路径资源。请注意,我将配置文件放在单独的目录下,该目录位于src/main/resources/custom-config中。
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext;
applicationContext = new SpringApplicationBuilder(YmlsApplication.class)
.properties("spring.config.name:applicationTest,CountriesData",
"spring.config.location:classpath:/custom-config/")
.build().run(args);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
MutablePropertySources sources = environment.getPropertySources();
sources.forEach(p -> System.out.println(p.getName()));
}注意路径中的classpath:,并使用/在资源的根级启动目录。
发布于 2018-09-18 08:52:48
您可以使用@PropertySource注释将配置外部化为属性文件。
Spring建议使用Environment来获取属性值。
env.getProperty("mongodb.db");您可以提到类中使用的属性文件。
@Configuration
@PropertySource({
"classpath:config.properties",
"classpath:db.properties"
})
public class AppConfig {
@Autowired
Environment env;
}从Spring 4开始,您可以使用ignoreResourceNotFound来忽略未找到的属性文件
@PropertySources({
@PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true),
@PropertySource("classpath:config.properties")示例来自于文章- https://www.mkyong.com/spring/spring-propertysources-example/。
如果需要更多信息,请参考本文,来自Spring文档
https://stackoverflow.com/questions/52381698
复制相似问题