簡體   English   中英

Spring 引導加載目錄中的所有屬性文件

[英]Spring boot load all properties files in directory

前:

我有一個很大的屬性文件,其中有我所有的屬性,我曾經像這樣加載:

@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()) {
    ...
}

每當我需要訪問一個值時,我都會調用env.getProperty("someKey")

后:

我不得不這樣做,而不是加載一個大的屬性文件,我需要制作多個較小的屬性文件並從同一個文件夾加載它們。

為此,我在我的 Config class 中手動配置了一個屬性配置 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;
}

到目前為止,一切都很好。 然后我定義了一個全局 map 變量來填充我的鍵值對。

@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());
    }
}

但是當我檢查 map 中的內容時,它是一堆像這樣的值:

java.vm.vendor: Oracle Corporation PROCESSOR_ARCHITECTURE: AMD64 PSModulePath: C:\Program Files\WindowsPowerShell\Modules;C:\windows\system32\WindowsPowerShell\v1.0\Modules user.variant: MAVEN_HOME: C:\Program Files\apache -maven-3.8.5 user.timezone:歐洲/巴黎

我期待它也充滿了我在文件中定義的屬性。

我錯過了什么? 我應該如何 go 關於這個?

查看創建 EnvironmentPostProcessor 以提供加載多個文件。 您可以控制順序並決定哪些屬性優先。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM