最近看《Professional Java Development with the Spring Framework》时看到了spring对底层资源的抽象,才找到了完美解决方案。
原来的代码:
public void setTemplatePath(String templatePath) {
this.templatePath = templatePath;
}
public void initListener() {
TemplateEventListener templateListener = new TemplateEventListener(){
public void handleTemplateEvent(TemplateEventSupport evt) {
// 添加事件到队列中
queue.offer(evt);
if(log.isDebugEnabled()){
log.debug("Add Template about:" + evt.getTemplateName());
}
}
};
//注册模版监听事件
templateManager.addEventListener(Constants.TEMPLATE_SAVE_EVENT, templateListener,false);
//设置freemarker的参数
freemarkerCfg = new Configuration();
try {
freemarkerCfg.setDirectoryForTemplateLoading(new File(templatePath));
freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
freemarkerCfg.setDefaultEncoding("UTF-8");
} catch (IOException ex) {
throw new SystemException("No Directory found,please check you config.");
}
}
<bean id="buildHtmlService" class="cn.jdk.leaf.service.impl.BuildHtmlServiceImpl" init-method="initListener">
<property name="templatePath"><value>${templatePath}</value></property>
</bean>
public void setTemplatePath(Resource templatePath) {
this.templatePath = templatePath;
}
public void initListener() {
TemplateEventListener templateListener = new TemplateEventListener(){
public void handleTemplateEvent(TemplateEventSupport evt) {
// 添加事件到队列中
queue.offer(evt);
if(log.isDebugEnabled()){
log.debug("Add Template about:" + evt.getTemplateName());
}
}
};
//注册模版监听事件
templateManager.addEventListener(Constants.TEMPLATE_SAVE_EVENT, templateListener,false);
//设置freemarker的参数
freemarkerCfg = new Configuration();
try {
freemarkerCfg.setDirectoryForTemplateLoading(templatePath.getFile());
freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
freemarkerCfg.setDefaultEncoding("UTF-8");
} catch (IOException ex) {
throw new SystemException("No Directory found,please check you config.");
}
}
<property name="templatePath"><value>${templatePath}</value></property>
</bean>
除经特别注明外,本文章版权归莫多泡泡所有. 署名,非商业用途,保持一致. somebody(莫多) |