hashvalue java,如何使用Spring @Value从Java属性文件填充HashMap

Is it possible to use Spring @Value, to map values from properties file to the 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.[]']}")

private final HashMap expirations = new HashMap();

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

name1 = 100

name2 = 20

解决方案

I make one solution inspired by the previous post.

Register property file in the Spring configuration:

And I create component:

@Component("PropertyMapper")

public class PropertyMapper {

@Autowired

ApplicationContext applicationContext;

public HashMap startWith(String qualifier, String startWith) {

return startWith(qualifier, startWith, false);

}

public HashMap startWith(String qualifier, String startWith, boolean removeStartWith) {

HashMap result = new HashMap();

Object obj = applicationContext.getBean(qualifier);

if (obj instanceof Properties) {

Properties mobileProperties = (Properties)obj;

if (mobileProperties != null) {

for (Entry 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;

}

}

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 portalExpirations;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值