Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load all key/value pairs in properties file

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
}
}
like image 213
Sajjad Avatar asked Feb 09 '23 02:02

Sajjad


2 Answers

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));
}
like image 134
Ken Bekov Avatar answered Feb 11 '23 05:02

Ken Bekov


You can autowire in an EnumerablePropertySource which contains the method getPropertyNames()

like image 44
Johan Sjöberg Avatar answered Feb 11 '23 04:02

Johan Sjöberg