在Spring中将属性文件中的所有键和值注入为Map

Ale*_*ava 1 java spring

有人可以提供一些想法来注入属性文件中的所有动态键和值,并将其传递MapDBConstants使用Setter Injection with Collection的类。

密钥事先未知,可能会有所不同。

// 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
Run Code Online (Sandbox Code Playgroud)

DBConstants 包含映射dbConstants,需要为其注入所有键和值。

请提供bean定义以将所有键和值注入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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mon*_*mul 5

您可以使用属性文件创建PropertiesFactoryBean,然后在要用作地图的位置添加@Resource批注。

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

用法:

@Resource(name = "myProperties")
private Map<String, String> myProperties;
Run Code Online (Sandbox Code Playgroud)

  • @Alex_Java:在上面的示例中和一般情况下,您可以使用 `Properties` 代替 `Map&lt;String, String&gt;`。 (2认同)