I need to get spring bean from WebApplicationContext
in macros.
My attempt is to do the following:
<#macro categoryName category>
<#assign context=springMacroRequestContext.webApplicationContext>
<#assign lb=context.getBean("localizationBean")/>
<#assign pp=context.getBean("phraseProvider")/>
<#assign categoryName=pp.getPhrase(lb.getCategoryMnemo(category))/>
${categoryName}
</#macro>
But this is failing. First of all if I provide a bean name which is a string to getBean
it returns an Object which I have to cast somehow, I've also tried to provide fully qualified class name but freemarker didn't like it. So how to do it ?
My solution to this problem was to pass a bean from controller and use it in a macros then.
Also I would suggest if you have for example User
entity in your domain to create a related macros file like user-macroses.ftl
where all user related macroses are placed.
And if in some of the macroses you need to call some spring bean method you should create a bean like UserFtlMacroses
where you put user related logic, so when on the view you call some macros <@user.doSomething/>
the macros doSomething
will call a method from UserFtlMacroses
.