Alex_Java
Alex_Java

Reputation: 23

Inject all keys and Values from property file as Map in Spring

Can someone provide some idea to inject all dynamic keys and values from property file and pass it as Map to DBConstants class using Setter Injection with Collection.

Keys are not known in advance and can vary.

// Example Property File that stores all db related details
// db.properties

db.username.admin=root
db.password.admin=password12
db.username.user=admin
db.password.user=password13

DBConstants contains map dbConstants for which all keys and values need to be injected.

Please provide bean definition to inject all keys and values to Map dbConstants.

public class DBConstants {

    private Map<String,String> dbConstants;

    public Map<String, String> getDbConstants() {
        return dbConstants;
    }

    public void setDbConstants(Map<String, String> dbConstants) {
        this.dbConstants = dbConstants;
    }
}

Upvotes: 2

Views: 9590

Answers (3)

Srikanth Reddy
Srikanth Reddy

Reputation: 1

you have to give spaces its like

hash.key = {indoor: 'reading', outdoor: 'fishing'}

Read map like below as i mentioned.

@Value("#{${hash.key}}")
private Map<String, String> hobbies;

Upvotes: 0

Marcos Nunes
Marcos Nunes

Reputation: 1355

you can use @Value.

Properties file:

dbConstants={key1:'value1',key2:'value2'}

Java code:

@Value("#{${dbConstants}}")
private Map<String,String> dbConstants;

Upvotes: 2

Monzurul Shimul
Monzurul Shimul

Reputation: 8396

You can create PropertiesFactoryBean with your properties file and then inject it with @Resource annotation where you want to use it as a map.

@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("prop_file_name.properties"));
    return bean;
}

Usage:

@Resource(name = "myProperties")
private Map<String, String> myProperties;

Upvotes: 7

Related Questions