spring关于底层资源的抽象

王朝other·作者佚名  2008-05-19
窄屏简体版  字體: |||超大  

在以前的项目中对于一些资源的配置基本上都是通过spring的IOC注入一个目录的地址字符串。而这样的问题是,对于开发中的团队来说还是很有问题的,因为每个可能都配置一个不同的本地目录,而发布到服务器之后又有不同的目录。这样造成每个人提交了配置文件之后其他人都可能需要修改配置文件才能正确启动服务。这确实很令人烦劳。

最近看《Professional Java Development with the Spring Framework》时看到了spring对底层资源的抽象,才找到了完美解决方案。

原来的代码:

privateStringtemplatePath;

publicvoidsetTemplatePath(StringtemplatePath){

this.templatePath=templatePath;

}

publicvoidinitListener(){

TemplateEventListenertemplateListener=newTemplateEventListener(){

publicvoidhandleTemplateEvent(TemplateEventSupportevt){

//添加事件到队列中

queue.offer(evt);

if(log.isDebugEnabled()){

log.debug("AddTemplateabout:"+evt.getTemplateName());

}

}

};

//注册模版监听事件

templateManager.addEventListener(Constants.TEMPLATE_SAVE_EVENT,templateListener,false);

//设置freemarker的参数

freemarkerCfg=newConfiguration();

try{

freemarkerCfg.setDirectoryForTemplateLoading(newFile(templatePath));

freemarkerCfg.setObjectWrapper(newDefaultObjectWrapper());

freemarkerCfg.setDefaultEncoding("UTF-8");

}catch(IOExceptionex){

thrownewSystemException("NoDirectoryfound,pleasecheckyouconfig.");

}

}

配置文件

<beanid="buildHtmlService"class="cn.jdk.leaf.service.impl.BuildHtmlServiceImpl"init-method="initListener">

<propertyname="templatePath"><value>${templatePath}</value></property>

</bean>

templatePath.path=D:/template

使用spring对底层资源的抽象只要把templatePath改成Resource就可以了

privateResourcetemplatePath;

publicvoidsetTemplatePath(ResourcetemplatePath){

this.templatePath=templatePath;

}

publicvoidinitListener(){

TemplateEventListenertemplateListener=newTemplateEventListener(){

publicvoidhandleTemplateEvent(TemplateEventSupportevt){

//添加事件到队列中

queue.offer(evt);

if(log.isDebugEnabled()){

log.debug("AddTemplateabout:"+evt.getTemplateName());

}

}

};

//注册模版监听事件

templateManager.addEventListener(Constants.TEMPLATE_SAVE_EVENT,templateListener,false);

//设置freemarker的参数

freemarkerCfg=newConfiguration();

try{

freemarkerCfg.setDirectoryForTemplateLoading(templatePath.getFile());

freemarkerCfg.setObjectWrapper(newDefaultObjectWrapper());

freemarkerCfg.setDefaultEncoding("UTF-8");

}catch(IOExceptionex){

thrownewSystemException("NoDirectoryfound,pleasecheckyouconfig.");

}

}

bean的配置不变,只要修改properties文件就可以了。

<beanid="buildHtmlService"class="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

这样就可以了。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航