1

我想知道是否有办法在调用 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的评估调用之后,我看到显示AppSpecificInvalidReferenceEventHandler正在工作的日志语句,但是如果我如上所述在Spring上下文中声明eventhandler.invalidreferences.class ,我看不到如何检索该类及其InvalidReferenceInfo列表。

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

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");

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

ec.getInvalidReferenceEventHandlers();

我在返回的迭代器中取回 AppSpecificInvalidReferenceEventHandler ......

4

0 回答 0