我有转换矩阵,每个coloumn和行索引表示为字符串,值为boolean。例如:
matrix["first_state"]["second_state"] = true;
matrix["first_state"]["second_state"] = false;
但java不支持带字符串索引的数组。所以我将转换矩阵推送到Map。
matrix.put(new Key("FirstOpenState", "ThirdGreenState"), false);
我有大约15个状态和大约300行描述转换矩阵的代码。我发现它很难看。
的问题: 的
将这些值推送到spring .properties的优雅方法是什么?
答案 0 :(得分:1)
直接映射也可能很难看。我只是将属性列为
outgoingTransitions.s1=s2,s5
outgoingTransitions.s2=s4,s1
然后将这些属性加载到Properties对象中,迭代键(s1),拆分值(s2,s5)并使用相应的Key
和布尔值填充矩阵映射。
这里有一些快速而肮脏的代码来演示,使用Guava进行字符串操作。
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
@Component
public class Foo {
@Autowired
@Qualifier("transitionProperties")
private Properties transitionProperties;
private Map<String, Set<String>> transitions = Maps.newHashMap();
@PostConstruct
public void loadTransitions() {
for (Map.Entry<Object, Object> transitionList : transitionProperties.entrySet()) {
String sourceState = (String) transitionList.getValue();
if (!transitions.containsKey(sourceState)) {
transitions.put(sourceState, Sets.<String>newHashSet());
}
Set<String> destinationStates = transitions.get(sourceState);
for (String destinationState : Splitter.on(',').split((String) transitionList.getValue())) {
destinationStates.add(destinationState);
}
}
}
public boolean isTransitionAllowed(String sourceState, String destinationState) {
Set<String> destinationStates = transitions.get(sourceState);
return destinationStates != null && destinationStates.contains(destinationState);
}
}