我尝试使用Spring SpEL来解析在UDP中收到的消息。
为了理解如何使用Spring SpEL,我写了这个:
context.xml中:
<bean id="message" class="springsimulator.Message">
<property name="strMessage" value="$TEST,11,22,33"/>
</bean>
<bean id="nmeamessage" class="springsimulator.NMEAMessage">
<property name="fields" value="#{message.strMessage.split(',')}"/>
</bean>
<bean id="parser" class="springsimulator.SPELParser">
<property name="values">
<map>
<entry key="val1" value="#{nmeamessage.fields[1]}"/>
<entry key="val2" value="#{nmeamessage.fields[2]}"/>
</map>
</property>
</bean>
Message.java:
public class Message {
public String strMessage;
public void setStrMessage(String strMessage) {
this.strMessage = strMessage;
}
}
NMEAMessage:
public class NMEAMessage {
public String[] fields;
public void setFields(String[] fields) {
this.fields = fields;
}
}
分析器:
public class Parser {
Map<String,String> values;
public void setValues(Map<String, String> values) {
this.values = values;
}
public String toString() {
String message = "";
for (Entry<String, String> entry : values.entrySet()) {
message += entry.getKey() + ":" + entry.getValue() + "\n";
}
return message;
}
}
主:
ExpressionParser parser = new SpelExpressionParser();
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
Parser myparser = (Parser) context.getBean("parser");
System.out.println(myparser);
这有效,我已经解析了我的信息。
但是现在,我希望每次收到消息时都在循环中评估SpEL表达式
while(running) {
socket.receive(message)
//Split message to get fields
//set fields into a map
}
使用SpEL和context.xml是否有正确的方法?
由于
答案 0 :(得分:3)
要在运行时解析SpEL表达式,请执行以下操作:
// Setup the SpEL parser: do this once
SpelParserConfiguration spelParserConfiguration = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, getClass().getClassLoader());
ExpressionParser expressionParser = new SpelExpressionParser(spelParserConfiguration);
StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
// Parse (compile) the expression: try to do this once
Expression expression = expressionParser.parseExpression(unevaluatedExpression)
// Then within the loop ...
// Supply context, like the value of your namespace
evaluationContext.setVariable(variableName, value);
// Evaluate an expression as many times as you like
Object result = expression.getValue(evaluationContext);