我有一个properties
文件,其中的值以逗号分隔。我能够获得如下的Object
值。谁能告诉我如何将值分开并以String形式获取。
.properties
key-1 = value1,value11
key-2 = value2,value22
key-3 = value3,value33
key-4 = value4,value44
代码
@PropertySource( value = "classpath:test1.properties", name = "test1" )
AbstractEnvironment ae = (AbstractEnvironment)env;
org.springframework.core.env.PropertySource test1Source =
ae.getPropertySources().get("test1");
Properties propsTest1 = (Properties)test1Source.getSource();
for(Object key : propsTest1.keySet()){
System.out.println("Properties file======> propsTest1.get(key));
}
答案 0 :(得分:3)
您可以将@Value
注释与@PropertySource
一起使用以获取属性的值。另外,您可以使用Spring Expression将其拆分为列表,例如:
@PropertySource( value = "classpath:test1.properties", name = "test1" )
public class PropertyClass {
@Value("#{'${key-1}'.split(',')}")
private List<String> key1Values;
}
这将为您提供针对key-1
配置的所有值的列表。
答案 1 :(得分:2)
您可以尝试以下类似方法。
Properties propsTest1 = (Properties)test1Source.getSource();
for(Map.Entry<Object, Object> e : propsTest1.entrySet()){
String value = (String)e.getValue();
String[] values = value.split(",");
// If you have spaces as between values, you have to take care of it.
}
答案 2 :(得分:1)
.properties
map.key[0] = value1,value11
map.key[1] = value2,value22
map.key[2] = value3,value33
map.key[3] = value4,value44
代码
@ConfigurationProperties(prefix="map")
public class YourConfig {
private List<String> keys = new ArrayList<String>();
public List<String> getKeys() {
return this.servers;
}
}
或者您可以使用:
keys={key-1:'value1',key-1:'value2',....}
代码
@Value("#{${keys}}") private Map<String,String> keys;