Does Spring put all properties into the same hashmap/list?
How can I get a list of all of the properties being managed by Spring
For example, if I have two properties files and they define overlapping properties which
// FILE: src/main/resources/file1.properties
prop1.color = red
prop1.fill = green
// FILE: src/main/resources/file2.properties
prop2.color = purple
prop1.fill = ORANGE
The configuration class used to tell Spring to read the two files is something like this:
@PropertySource("classpath:file1.properties")
@PropertySource("classpath:file2.properties")
@Configuration
public class MyConfig {
}
My question is Can I get an iterator to access all of the properties defined? If so how.
Searching for answer
So far I haven't found a solution to this question.
I did an Internet search for "stack overflow Spring properties" and did not found the answer.
Some SO questions I found are:
- Spring boot get all properties from properties file and load into hashmap
- Spring Boot application.properties
But they didn't answer my question
CodePudding user response:
Spring provides a PropertySources
interface which is implemented by the MutablePropertySources
class. This class basically just holds a list of PropertySource
instances (e.g. instances of the PropertiesPropertySource
class) and provides methods for iterating over these instances.
If you look at the implementation of MutablePropertySources
you can see that there are multiple methods for adding PropertySource
instances at different positions and relative to other PropertySource
s in that list. If you want to get a property, the get
method of the MutablePropertySources
is called which iterates over all PropertySource
s until it finds that property.
Then there is the Environment
interface that is implemented by the abstract class AbstractEnvironment
. You can use the latter to access the PropertySources
instance.
For example, you can do:
@PropertySource("classpath:file1.properties")
@PropertySource("classpath:file2.properties")
@Configuration
public class ExampleConfig {
@Autowired
public ExampleConfig(Environment environment) {
AbstractEnvironment env = (AbstractEnvironment) environment;
for (org.springframework.core.env.PropertySource<?> source : env.getPropertySources()) {
if (source instanceof MapPropertySource mapPropertySource) {
System.out.println(mapPropertySource.getSource());
}
}
}
}
You can check out the org.springframework.core.env
package which contains all of these classes.
So, to answer your first answer more explicitly: No, Spring does not put all properties into a single map. It puts properties from different locations into different PropertySource
s which are then added to a PropertySources
instance.