【问题标题】:Camel Velocity Template - access java object propertiesCamel Velocity Template - 访问 java 对象属性
【发布时间】:2014-10-22 10:04:24
【问题描述】:

我有一条骆驼路线,它使用 Velocity 模板,在正文中我有一个对象定义如下:

class MailImpl extends AbstractMail{

    private BodyContext bodyContext;

    public BodyContext getBodyContext() {
        return bodyContext;
    }

    public void setBodyContext(BodyContext bodyContext) {
        this.bodyContext = bodyContext;
    }

    private String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }

    @Override
    public String toString() {
        return "MailImpl{" +
                "bodyContext=" + bodyContext +
                '}';
    }
}

class BodyContext{
    private String value;

    public BodyContext(String value) {
        this.value = value;
    }

    public BodyContext() {
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "BodyContext{" +
                "value='" + value + '\'' +
                '}';
    }

在速度模板中,我想访问 MailImpl 对象属性,例如我使用 ${body.test} 和 ${body.bodyContext.value} 但速度模板不会转换这些值(它返回为字符串 $ {body.test} 和 ${body.bodyContext.value})。

一种解决方案可能是为我需要在模板中使用的每个值创建标题,但由于我的路线是动态的(我根据标题选择速度模板)我想在速度上下文中访问正文属性.这有可能吗?

【问题讨论】:

    标签: apache-camel velocity


    【解决方案1】:

    您可以通过设置消息头 "CamelVelocityContext" 来设置自定义 Velocity 上下文(自 Camel v2.14 起)。来自骆驼的test case

    Map<String, Object> variableMap = new HashMap<String, Object>();
    Map<String, Object> headersMap = new HashMap<String, Object>();
    headersMap.put("name", "Willem");
    variableMap.put("headers", headersMap);
    variableMap.put("body", "Monday");
    variableMap.put("exchange", exchange);
    VelocityContext velocityContext = new VelocityContext(variableMap);
    exchange.getIn().setHeader(VelocityConstants.VELOCITY_CONTEXT, velocityContext);
    exchange.setProperty("item", "7");
    

    使用以下模板:

    Dear ${headers.name}. You ordered item ${exchange.properties.item} on ${body}.
    

    你得到:

    Dear Willem. You ordered item 7 on Monday.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-05
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多