10

这是我的对象类:

public class Address
{
    public final String line1;
    public final String town;
    public final String postcode;

    public Address(final String line1, final String town, final String postcode)
    {
        this.line1 = line1;
        this.town = town;
        this.postcode = postcode;
    }
}

我将它添加到速度上下文中,如下所示:

Address theAddress = new Address("123 Fake St", "Springfield", "SP123");
context.put("TheAddress", theAddress);

但是,在编写模板时,以下内容不会呈现地址字段(但是,当我将 getter 添加到 Address 类时它可以正常工作)

<Address>
    <Line1>${TheAddress.line1}</Line1>
    <Town>${TheAddress.town}</Town>
    <Postcode>${TheAddress.postcode}</Postcode>
</Address>

是否可以在不添加 getter 的情况下从 Velocity 访问对象上的公共字段?

4

4 回答 4

4

默认情况下不是。您需要配置不同的 Uberspect 实现。

于 2013-06-12T15:22:42.800 回答
4

Velocity 用户指南表明这是不可能的。引用:

[Velocity] 根据几个既定的命名约定尝试不同的替代方案。确切的查找顺序取决于属性名称是否以大写字母开头。对于小写名称,例如 $customer.address,序列为

  1. 获取地址()
  2. 获取地址()
  3. 得到(“地址”)
  4. 是地址()

对于像 $customer.Address 这样的大写属性名称,它略有不同:

  1. 获取地址()
  2. 获取地址()
  3. 得到(“地址”)
  4. 是地址()
于 2013-06-12T15:34:05.353 回答
0

http://wiki.apache.org/velocity/VelocityFAQ

问:如何在模板中访问对象的公共字段?

A:目前,您有三种选择:

FieldMethodizer仅适用于公共静态字段。

PublicFieldUberspect示例代码很旧,它只是在不存在的字段上出现错误而失败。

忘记开发列表中的大厅。)


同时,当前速度主干中有UberspectPublicFields的良好缓存实现。不幸的是,多年来没有积极的开发,也没有发布下一个版本的计划。必须自己构建它并捆绑在私有存储库中。


另一个替代方案是具有额外 scala 兼容性的分叉,可在中央 maven 存储库中获得: https ://mvnrepository.com/artifact/com.sksamuel.scalocity/scalocity/0.9 。

插入而不是通常的速度依赖:

<dependency>
  <groupId>com.sksamuel.scalocity</groupId>
  <artifactId>scalocity</artifactId>
  <version>0.9</version>
</dependency>

然后只需添加velocity.properties

runtime.introspector.uberspect = org.apache.velocity.util.introspection.UberspectPublicFields, org.apache.velocity.util.introspection.UberspectImpl

需要注意的是,该UberspectImpl补丁添加了对 scala 属性的额外支持,并且需要 8 MB scala jar。


最终,我只是将以下课程从速度主干实习到自己的项目中:

org.apache.velocity.runtime.parser.node.PublicFieldExecutor org.apache.velocity.runtime.parser.node.SetPublicFieldExecutor org.apache.velocity.util.introspection.ClassFieldMap org.apache.velocity.util.introspection.Introspector org. apache.velocity.util.introspection.IntrospectorBase org.apache.velocity.util.introspection.IntrospectorCache org.apache.velocity.util.introspection.IntrospectorCacheImpl org.apache.velocity.util.introspection.UberspectPublicFields

这些适用于 Velocity 1.7。

于 2015-07-03T17:22:52.270 回答
0

我做

import org.apache.velocity.util.introspection.UberspectImpl;
import org.apache.velocity.util.introspection.UberspectPublicFields;

....

properties.setProperty("runtime.introspector.uberspect",
  UberspectImpl.class.getName() + ", " +
  UberspectPublicFields.class.getName());

一切正常!!!

于 2018-08-18T11:00:00.737 回答