Issue
Before:
I had a big properties file in which I had all my properties, which I used to load like this:
@PropertySource(value = "file:C:\\Users\\xxx\\yyy\\conf\\context.properties", name = "cntx.props")
and then get my properties like this:
AbstractEnvironment ae = (AbstractEnvironment)env;
PropertySource source = ae.getPropertySources().get("cntx.props");
Properties properties = (Properties)source.getSource();
for(Object key : properties.keySet()) {
...
}
and i would call env.getProperty("someKey")
whenever I need to access a value.
After:
I had to make it as such instead of loading one big properties files, I would need to make multiple smaller properties files and load them from the same folder.
For that I configured a property configuration bean manually in my Config class:
@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;
}
So far so good. I then defined a global map variable to fill it with my key value pairs.
@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());
}
}
But when I check what's in the map, it's a bunch of values like this:
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 : Europe/Paris
I was expecting it too be filled with the properties I defined in my files.
What am I missing? How should I go about this?
Solution
Look at creating an EnvironmentPostProcessor to provide for loading multiple files. You'll have control of the order and decide which properties will take precedence.
Answered By - Corneil du Plessis
Answer Checked By - Marilyn (JavaFixing Volunteer)