Freemarker-仅将getter用于bean [英] Freemarker - only use getter for beans
问题描述
我的实体中有一些构建器功能,freemarker无法处理.
I have some builder functions in my entities, which cannot be handled by freemarker.
例如,我有以下bean/实体:
For example, I have the following bean/entity:
public class User{
private Long number;
public Long getNumber(){
return this.number;
}
public void setNumber(Long number){
this.number = number;
}
public User number(Long number){
this.number = number;
}
}
我的自由标记模板是这样的:
And my freemarker template is something like this:
<span>${user.number}</span>
我将如下进行动态处理:
which I process on the fly as follows:
User user = getUser();
Map<String, Object> context = new HashMap<>();
contaxt.put("user", user);
Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
configuration.setObjectWrapper(new BeansWrapper(Configuration.VERSION_2_3_0));
Template t = new Template("usertpl", template, configuration);
String result = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
由于我的实体包含方法"number(Long)",因此freemarker尝试使用此方法,该方法实际上是一个setter方法-因此不起作用.
Since my entity contains a method "number(Long)", freemarker tries to use this, which is actually a setter - so it is not working.
我知道,我可以在模板中使用getter,但是模板应该由用户定义(对于那些不是程序员的人,我认为${user.number}
比${user.getNumber()}
更容易理解)
I know, that i can use the getter in the template, but the template should be defined by users (where I think ${user.number}
is more comprehensible than ${user.getNumber()}
for those who are not programmers)
所以,我正在寻找另一种解决方案...
So, I'm searching for another solution...
是否可以配置freemarker,使其仅使用getter(getNumber()
)来访问属性,而不使用number(Long)
?
Is there a possibility to configure freemarker so that it only uses the getter (getNumber()
) to access the property, instead of using the number(Long)
?
推荐答案
您可以使用setMethodAppearanceFineTuner
像这样配置BeansWrapper
.为了方便复制粘贴,在这里我将使用构建器代替new
,DefaultObjectWrapper
代替BeansWrapper
和VERSION_2_3_25
代替VERSION_2_3_0
,但这也适用于您的设置:>
You can configure BeansWrapper
like that with setMethodAppearanceFineTuner
. For the sake of hasty copy-pasters, I will use here a builder instead of new
, DefaultObjectWrapper
instead of BeansWrapper
, and VERSION_2_3_25
instead of VERSION_2_3_0
, but this also works with your setup:
DefaultObjectWrapperBuilder owb = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
owb.setMethodAppearanceFineTuner(new MethodAppearanceFineTuner() {
@Override
public void process(MethodAppearanceDecisionInput in, MethodAppearanceDecision out) {
out.setMethodShadowsProperty(false);
}
});
cfg.setObjectWrapper(owb.build());
就JavaDoc中的实验性"免责声明而言,请放心,这些免责声明将在2.3.26版中处于实验状态.
As of the "experimental" disclaimers in the JavaDoc, don't worry, these will leave experimental status in 2.3.26.
这篇关于Freemarker-仅将getter用于bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!