Spring引导加载目录中的所有属性文件



之前:

我有一个大的属性文件,里面有我所有的属性,我曾经这样加载:

@PropertySource(value = "file:C:\Users\xxx\yyy\conf\context.properties", name = "cntx.props")

然后得到我的属性如下:

AbstractEnvironment ae = (AbstractEnvironment)env;
PropertySource source = ae.getPropertySources().get("cntx.props");
Properties properties = (Properties)source.getSource();
for(Object key : properties.keySet()) {
...
}

每当我需要访问一个值时,我就会调用CCD_ 1。

之后:

我必须这样做,而不是加载一个大的属性文件,我需要制作多个较小的属性文件并从同一文件夹加载它们。

为此,我在Config类中手动配置了一个属性配置bean:

@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() throws NamingException {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
File dir = new File("C:\Users\xxx\yyy\conf");
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".properties");
}
});
FileSystemResource[] resources = new FileSystemResource[files.length];
for (int i = 0; i < resources.length; i++) {
resources[i] = new FileSystemResource(files[i].getAbsolutePath());
}
properties.setLocations(resources);
properties.setIgnoreUnresolvablePlaceholders(true);
return properties;
}

到目前为止还不错。然后,我定义了一个全局映射变量,用键值对填充它。

@Bean
public void getPropsFromFile() {
propertiesMap = new HashMap();
for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
org.springframework.core.env.PropertySource propertySource = (org.springframework.core.env.PropertySource) it.next();
if (propertySource instanceof MapPropertySource) {
propertiesMap.putAll(((MapPropertySource) propertySource).getSource());
}
}
// check what's in the map
for (String key : propertiesMap.keySet()) {
System.out.println(key + " : " + propertiesMap.get(key).toString());
}
}

但当我检查地图上的内容时,它是一堆这样的值:

java.vm供应商:Oracle Corporation PROCESSOR_ARCHITECTURE:AMD64PS模块路径:C:\ProgramFiles\WindowsPowerShell \模块;C: \windows\system32\WindowsPowerShell\v1.0\模块user.variant:MAVEN_HOME:C:\Program Files\apache-MAVEN-3.8.5user.timezone:欧洲/巴黎

我希望它也能填充我在文件中定义的属性。

我错过了什么?我该怎么做?

考虑创建一个EnvironmentPostProcessor来提供加载多个文件的功能。您可以控制顺序,并决定哪些属性优先。

最新更新