Spring Boot-添加外部属性文件 [英] Spring Boot - add external property files
问题描述
我在SpringBoot中有一个简单的MVC应用程序,是使用java-config创建的(我没有web.xml)。
该应用程序具有基于JPA的数据库连接。到目前为止,一切都很好,但是现在我必须将db.properties从WAR内部移动到OS变量指定的位置( CONFIG_LOCATION)。
在 spring doc 的描述并不太多。只能说这是可能的,但是我应该如何在Spring应用程序中设置它呢?
我想应该在初始化之前完成。
然后我只看到两个选项:
-SpringApplication-在某个地方应该从OS变量中插入文件位置,但找不到,
-一些注释,这将使OS变量不足,并在创建EntityManager之前将其添加到Spring上下文中。
I have simple MVC application in SpringBoot, created using java-config (I don't have web.xml).
That application have DB connection based on JPA. Until now, all was great, but now I must move db.properties from inside of WAR to location specified by OS variable ("CONFIG_LOCATION").
In spring doc is written about that not too much. There is only say that it is posible, but how I should set that in my Spring application?
I suppose that should be done before initializer.
Then I see only two options:
- SpringApplication - there is somewhere a place where I should insert files location from OS variable but I can't find it,
- some annotation, that will understond OS variable, and add files from it to spring context before EntityManager will be created.
我很乐意建议我该怎么做。
I'm open to suggestion how should I do that.
推荐答案
好,我找到了一种方法。
Ok, I found a way.
我创建了类,返回什么PropertySourcesPlaceholderConfigurer。
在该PSPC中,我获取OS变量,并扫描该位置中的所有文件。
扫描后,我将所有具有属性扩展名的文件添加到PSCS作为位置。 br />
方法是@Bean,类是@Configuration。之后一切正常:)
I created class what return PropertySourcesPlaceholderConfigurer.
In that PSPC i get OS variable, and scan all files in that location.
After scan I was add all files with properties extension to PSCS as locations.
Method is @Bean, and class is @Configuration. After that all works fine :)
imports...
@Configuration
public class AppServiceLoader {
@Bean(name = "propLoader")
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
String mainConfigPath = StringUtils.isNotEmpty(System.getenv("CONFIG_LOCATION"))
? System.getenv("CONFIG_LOCATION") : System.getProperties().getProperty("CONFIG_LOCATION");
File configFolder = new File(mainConfigPath);
if(configFolder.isDirectory()) {
FilenameFilter ff = new FilenameFilter() {
@Override
public boolean accept(File file, String string) {
return string.endsWith(".properties");
}
};
File[] listFiles = configFolder.listFiles(ff);
Resource[] resources = new Resource[listFiles.length];
for (int i = 0; i < listFiles.length; i++) {
if(listFiles[i].isFile()) {
resources[i] = new FileSystemResource(listFiles[i]);
}
}
pspc.setLocations(resources);
}
pspc.setIgnoreUnresolvablePlaceholders(true);
return pspc;
}
}
这篇关于Spring Boot-添加外部属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!