如何使用Spring @Value从Java属性文件填充HashMap [英] How to fill HashMap from java property file with Spring @Value
问题描述
是否可以使用Spring @Value将值从属性文件映射到HashMap.
Is it possible to use Spring @Value, to map values from properties file to the HashMap.
目前我有类似的东西,映射一个值不是问题. 但是我需要在HashMap到期中映射自定义值. 这样可能吗?
Currently I have something like this, and mapping one value is not a problem. But I need to map custom values in HashMap expirations. Is something like this possible?
@Service
@PropertySource(value = "classpath:my_service.properties")
public class SomeServiceImpl implements SomeService {
@Value("#{conf['service.cache']}")
private final boolean useCache = false;
@Value("#{conf['service.expiration.[<custom name>]']}")
private final HashMap<String, String> expirations = new HashMap<String, String>();
属性文件:"my_service.properties"
Property file: 'my_service.properties'
service.cache=true
service.expiration.name1=100
service.expiration.name2=20
是否可以像这样的键:值集进行映射
Is it posible to map like this key:value set
-
名称1 = 100
name1 = 100
name2 = 20
name2 = 20
推荐答案
我提出了一个受前一篇文章启发的解决方案.
I make one solution inspired by the previous post.
在Spring配置中注册属性文件:
Register property file in the Spring configuration:
<util:properties id="myProp" location="classpath:my.properties"/>
然后我创建组件:
@Component("PropertyMapper")
public class PropertyMapper {
@Autowired
ApplicationContext applicationContext;
public HashMap<String, Object> startWith(String qualifier, String startWith) {
return startWith(qualifier, startWith, false);
}
public HashMap<String, Object> startWith(String qualifier, String startWith, boolean removeStartWith) {
HashMap<String, Object> result = new HashMap<String, Object>();
Object obj = applicationContext.getBean(qualifier);
if (obj instanceof Properties) {
Properties mobileProperties = (Properties)obj;
if (mobileProperties != null) {
for (Entry<Object, Object> e : mobileProperties.entrySet()) {
Object oKey = e.getKey();
if (oKey instanceof String) {
String key = (String)oKey;
if (((String) oKey).startsWith(startWith)) {
if (removeStartWith)
key = key.substring(startWith.length());
result.put(key, e.getValue());
}
}
}
}
}
return result;
}
}
当我想将所有以specifix值开头的属性映射到带有@Value注释的HashMap时:
And when I want to map all properties that begin with specifix value to HashMap, with @Value annotation:
@Service
public class MyServiceImpl implements MyService {
@Value("#{PropertyMapper.startWith('myProp', 'service.expiration.', true)}")
private HashMap<String, Object> portalExpirations;
这篇关于如何使用Spring @Value从Java属性文件填充HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!