Search code examples
javaspringspring-mvcspring-boot

How to read multiple properties with same prefix in java spring?


I am having the property file with the following values. I want to read all the properties with same prefix excluding others using spring mvc.

test.cat=cat
test.dog=dog
test.cow=cow
birds=eagle

Environment.getProperty("test.cat");

This will return only 'cat' .

In the above property file, I want to get all the properties starting(prefix) with test excluding birds. In spring boot we can achieve this with @ConfigurationProperties(prefix="test"), but how to achieve the same in spring mvc.


Solution

  • See this Jira ticket from Spring project for explanation why you don't see a method doing what you want. The snippet at the above link can be modified like this with an if statement in innermost loop doing the filtering. I assume you have a Environment env variable and looking for String prefix:

    Map<String, String> properties = new HashMap<>();
    if (env instanceof ConfigurableEnvironment) {
        for (PropertySource<?> propertySource : ((ConfigurableEnvironment) env).getPropertySources()) {
            if (propertySource instanceof EnumerablePropertySource) {
                for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
                    if (key.startsWith(prefix)) {
                        properties.put(key, propertySource.getProperty(key));
                    }
                }
            }
        }
    }