如何从Velocity Engine中检索无效引用?

时间:2012-10-30 05:25:39

标签: velocity

我想知道在调用VelocityEngine.evaluate之后是否有办法在Velocity中检索无效引用列表。

Velocity Eventhandler有一些很好的信息,关于创建我在VelocityEngine中使用的 AppSpecificInvalidReferenceEventHandler ,如下所示。

<bean id="templateVelocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
    <property name="velocityProperties">
        <props>
            <prop key="resource.loader">class</prop>
            <prop key="class.resource.loader.class">org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</prop>
            <prop key="class.resource.loader.cache">true</prop>         
            <prop key="eventhandler.invalidreferences.class">xyz.util.AppSpecificInvalidReferenceEventHandler,org.apache.velocity.app.event.implement.ReportInvalidReferences</prop>
        </props>
    </property>     
</bean>

在velocity的evaluate调用之后,我看到显示AppSpecificInvalidReferenceEventHandler正在运行的日志语句,但如果我声明了 eventhandler.invalidreferences.class 在上面的Spring上下文中。

填充和评估模板如下所示: -

VelocityContext context = new VelocityContext();
StringWriter bodyWriter = new StringWriter();

context.put("body", "some body text!");

boolean result = templateVelocityEngine.evaluate(context, bodyWriter, "logTag", "template ${body} text here loaded from a file");

所以我想做类似以下的事情(ec.getInvalidReferenceEventHandlers()除外)

EventCartridge ec = context.getEventCartridge();
Iterator it = ec.getInvalidReferenceEventHandlers();

while (it.hasNext()) {
    Object obj = it.next();

    if (obj instanceof ReportInvalidReferences) {
        AppSpecificInvalidReferenceEventHandler handler = (AppSpecificInvalidReferenceEventHandler) obj;
        List invalidRefs = handler.getInvalidReferences();

        if (!invalidRefs.isEmpty()) {
            // process the list of invalid references here
        }
    }
}

到目前为止我发现的唯一方法是不在Spring bean中声明 eventhandler.invalidreferences.class ,而是我会做以下

ReportInvalidReferences reporter = new AppSpecificInvalidReferenceEventHandler();
EventCartridge ec = new EventCartridge();
ec.addEventHandler(reporter);
ec.attachToContext(context);
VelocityContext context = new VelocityContext();
StringWriter bodyWriter = new StringWriter();

context.put("body", "some body text!");

boolean result = templateVelocityEngine.evaluate(context, bodyWriter, "logTag", "template ${body} text here loaded from a file");

使用上面的额外的Velocity评估设置代码(并在Spring bean中注释 eventhandler.invalidreferences.class ),然后我可以调用

ec.getInvalidReferenceEventHandlers();

我在Iterator中返回了AppSpecificInvalidReferenceEventHandler ...

0 个答案:

没有答案