FreeMarker自定义指令目前大多项目都需要在XML中配置,比如
<property name="freemarkerVariables"> <map> <entry key="xml_escape" value-ref="fmXmlEscape" /> </map> </property> <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
使用自动加载只需要制定好一定的规则,就可以在每次工程启动时自动加载所有自定义指令。
在与Spring集成使用时,完全可以借助Spring的按基类注入特性,将所有实现自定义指令的bean注入到FreeMarker的ShareVariables中,这样节省部分开发人员的工作,也防止指令过多后管理不便,以下是从PublicCMS中截取的代码实现
package com.sanluan.common.handler; import static org.apache.commons.logging.LogFactory.getLog; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import freemarker.template.SimpleHash; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateModelException; @Component public class FreeMarkerExtendHandler implements ApplicationContextAware { private final Log log = getLog(getClass()); @Autowired private Map<String, TemplateDirectiveModel> directiveMap; @Autowired private FreeMarkerConfigurer freeMarkerConfigurer; @Override public void setApplicationContext(ApplicationContext applicationcontext) throws BeansException { log.info("Freemarker directives and methods Handler started"); Map<String, Object> freemarkerVariables = new HashMap<String, Object>(); StringBuffer directives = new StringBuffer(); for (Entry<String, TemplateDirectiveModel> entry : directiveMap.entrySet()) { freemarkerVariables.put(entry.getKey(), entry.getValue()); if (0 != directives.length()) directives.append(","); directives.append(entry.getKey()); } try { freeMarkerConfigurer.getConfiguration().setAllSharedVariables( new SimpleHash(freemarkerVariables, freeMarkerConfigurer.getConfiguration().getObjectWrapper())); log.info((directiveMap.size()) + " directives created:[" + directives.toString() + "];"); } catch (TemplateModelException e) { } } }
标签:PublicCMS
1条评论
这个术语我知道!自动加载!
发表评论