最近看《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(莫多) |