I'm trying to load all key/value
pairs in my properties file.
One approach is that I load all the properties using @Value
manually, but for that I should know all the keys.
I cannot do this, since property file may be changed in future to include more set of key/value
pairs and I may need to modify code
again to accommodate them.
Second approach is that I should some how load the properties file and Iterate over it to load all the key/value
pairs without knowing the keys.
Say I have following properties file sample.properties
property_set.name="Database MySQL"
db.name=
db.url=
db.user=
db.passwd=
property_set.name="Database Oracle"
db.name=
db.url=
db.user=
db.passwd=
Here is what I'm trying to do
@Configuration
@PropertySource(value="classpath:sample.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public void loadConfig(){
//Can I some how iterate over the loaded sampe.properties and load all
//key/value pair in Map<String,Map<String, String>>
// say Map<"Database MySQL", Map<key,vale>>
// I cannot get individual properties like env.getProperty("key");
// since I may not know all the keys
}
}
Spring stores all properties in Environment
.
Environment
contains collection of PropertySource
. Every PropertySource
contains properties from specific source. There are system properties, and java environment properties and many other. Properties from you file will be there as well.
Any source has own name. In your case automatically generated name will be look like "class path resource [sample.properties]"
. As you see, the name is not so convenient. So lets set more convenient name:
@PropertySource(value="classpath:sample.properties", name="sample.props")
Now you can get source by this name:
AbstractEnvironment ae = (AbstractEnvironment)env;
org.springframework.core.env.PropertySource source =
ae.getPropertySources().get("sample.props");
Properties props = (Properties)source.getSource();
Note that I specified full name of PropertySource
class, to avoid conflict with @PropertySource annotation class. After that, you can work with properties. For example output them to console:
for(Object key : props.keySet()){
System.out.println(props.get(key));
}
You can autowire
in an EnumerablePropertySource which contains the method getPropertyNames()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With