[英]Inject all keys and Values from property file as Map in Spring
有人可以提供一些想法来从属性文件中注入所有动态键和值,并使用带有集合的 Setter 注入将其作为Map
传递给DBConstants
类。
密钥是事先不知道的,并且可能会有所不同。
// 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
包含需要为其注入所有键和值的映射 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;
}
}
您可以使用属性文件创建PropertiesFactoryBean,然后在要用作地图的位置添加@Resource批注。
@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("prop_file_name.properties"));
return bean;
}
用法:
@Resource(name = "myProperties")
private Map<String, String> myProperties;
您可以使用@Value
。
属性文件:
dbConstants={key1:'value1',key2:'value2'}
Java代码:
@Value("#{${dbConstants}}")
private Map<String,String> dbConstants;
你必须给空间它的样子
hash.key = {indoor: 'reading', outdoor: 'fishing'}
正如我提到的,阅读下面的地图。
@Value("#{${hash.key}}")
private Map<String, String> hobbies;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.