最近看Professional Java Development with the Spring Framework时看到了spring对底层资源抽象才找到了完美解决方案
原来代码:
privateStringtemplatePath;
publicvoidTemplatePath(StringtemplatePath){
this.templatePath=templatePath;
}
publicvoidinitListener{
TemplateEventListenertemplateListener=TemplateEventListener{
publicvoidhandleTemplateEvent(TemplateEventSupportevt){
//添加事件到队列中
queue.offer(evt);
(log.isDebugEnabled){
log.debug("AddTemplateabout:"+evt.getTemplateName);
}
}
};
//注册模版监听事件
templateManager.addEventListener(Constants.TEMPLATE_SAVE_EVENT,templateListener,false);
//设置freemarker参数
freemarkerCfg=Configuration;
try{
freemarkerCfg.DirectoryForTemplateLoading(File(templatePath));
freemarkerCfg.ObjectWrapper(DefaultObjectWrapper);
freemarkerCfg.DefaultEncoding("UTF-8");
}catch(IOExceptionex){
throwException("NoDirectoryfound,pleasecheckyouconfig.");
}
}
配置文件
<beanid="buildHtmlService"="cn.jdk.leaf.service.impl.BuildHtmlServiceImpl"init-method="initListener">
<propertyname="templatePath"><value>${templatePath}</value></property>
</bean>
templatePath.path=D:/template
使用spring对底层资源抽象只要把templatePath改成Resource就可以了
privateResourcetemplatePath;
publicvoidTemplatePath(ResourcetemplatePath){
this.templatePath=templatePath;
}
publicvoidinitListener{
TemplateEventListenertemplateListener=TemplateEventListener{
publicvoidhandleTemplateEvent(TemplateEventSupportevt){
//添加事件到队列中
queue.offer(evt);
(log.isDebugEnabled){
log.debug("AddTemplateabout:"+evt.getTemplateName);
}
}
};
//注册模版监听事件
templateManager.addEventListener(Constants.TEMPLATE_SAVE_EVENT,templateListener,false);
//设置freemarker参数
freemarkerCfg=Configuration;
try{
freemarkerCfg.DirectoryForTemplateLoading(templatePath.getFile);
freemarkerCfg.ObjectWrapper(DefaultObjectWrapper);
freemarkerCfg.DefaultEncoding("UTF-8");
}catch(IOExceptionex){
throwException("NoDirectoryfound,pleasecheckyouconfig.");
}
}
bean配置不变只要修改properties文件就可以了
<beanid="buildHtmlService"="cn.jdk.leaf.service.impl.BuildHtmlServiceImpl"init-method="initListener">
<propertyname="templatePath"><value>${templatePath}</value></property>
</bean>
把properties文件修改成
templatePath.path=template
在webcontext目录下面建立个template目录就可以了在部署到服务器时候需要部署到个特定目录只要修改这个配置文件为
templatePath.path=file:/D:/template
这样就可以了
最新评论