简体   繁体   中英

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
}
}

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));
}

您可以在包含方法getPropertyNames()EnumerablePropertySourceautowire

you can look up the class Properties in the jdk api and use the method load(InputStream inStream)

InputStream in = new FileInputStream("your properties location");
Properties prop = new Properties();
prop.load(in);

ps: prop is subClass of HashTable and don't forget to close stream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM