问题
I have some builder functions in my entities, which cannot be handled by freemarker.
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);
Since my entity contains a method "number(Long)", freemarker tries to use this, which is actually a setter - so it is not working.
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...
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)
?
回答1:
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());
As of the "experimental" disclaimers in the JavaDoc, don't worry, these will leave experimental status in 2.3.26.
来源:https://stackoverflow.com/questions/39747696/freemarker-only-use-getter-for-beans