繁体   English   中英

Spring SpEL - 如何使用SpEL来解析消息

[英]Spring SpEL - How to use SpEL to parse a message

我正在尝试使用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?

谢谢

要在运行时解析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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM