5
我在調查使用FreeMarker編寫EDI文件。這些基本上是格式嚴格(和驗證)的電子發票。我決定從寫一個簡單的例子開始,並堅持讓它模板化一個'嵌套pojo'。我的意思是一個POJO包含POJO,其中這兩個數據都有我想要的數據。我寫了一個未知原因的單元測試(自包含的)。當我運行測試時,我得到以下例外:如何使用FreeMarker來模板嵌套Pojos?
Expression user.getSub is undefined on line 1, column 24 in simple.
The problematic instruction:
----------
==> ${user.getSub().user} [on line 1, column 22 in simple]
----------
Java backtrace for programmers:
----------
freemarker.core.InvalidReferenceException: Expression user.getSub is undefined on line 1, column 24 in simple.
at freemarker.core.TemplateObject.assertNonNull(TemplateObject.java:124)
at freemarker.core.TemplateObject.invalidTypeException(TemplateObject.java:134)
<snip>
example.TestFreeMarkerTemplating.testSimpleTemplate(TestFreeMarkerTemplating.java:23)
<snip>
我已經嘗試了許多變化的模板,並沒有遇到成功。這是測試:
package example;
import java.io.*;
import org.junit.Test;
import freemarker.cache.StringTemplateLoader;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.*;
import static org.junit.Assert.*;
public class TestFreeMarkerTemplating {
Configuration cfg = new Configuration();
StringTemplateLoader stringLoader = new StringTemplateLoader();
{ cfg.setTemplateLoader(stringLoader);
cfg.setObjectWrapper(new BeansWrapper()); }
@Test
public void testSimpleTemplate() throws TemplateException, IOException{
stringLoader.putTemplate("simple", "Welcome ${user}. Sub ${user.getSub().user}");
Template temp = cfg.getTemplate("simple");
StringWriter out = new StringWriter();
temp.process(new TestPojo(), out);
assertEquals("Welcome Andy. Sub Bill", out.toString());
}
public static class TestPojo {
private final String user = "Andy";
private final SubPojo sub = new SubPojo();
public String getUser() { return user; }
public SubPojo getSub() { return sub; }
}
public static class SubPojo {
private final String user = "Bill";
public String getUser() { return user; }
}
}
感謝您的任何幫助!
謝謝。我一直盯着這個這麼久,我確信自己FreeMarker是錯的。你的回答很清楚,非常感謝。 – Spina