javaspringspring-mvcspring-boot

How to read multiple Spring properties with same prefix in Java


I have a properties file with the following values:

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

I want to read properties with Spring MVC:

import org.springframework.core.env.Environment;
...
Environment.getProperty("test.cat");

This will return only "cat".

How can I get all the properties starting with prefix test., thus excluding birds?

In Spring Boot we can achieve this with @ConfigurationProperties(prefix="test"), but how can I do it with 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));
                    }
                }
            }
        }
    }