spring资源文件:spring有关底层资源的抽象

  在以前项目中对于些资源配置基本上都是通过springIOC注入个目录地址而这样问题是对于开发中团队(Team)来说还是很有问题每个可能都配置个区别本地目录而发布到服务器的后又有区别目录这样造成每个人提交了配置文件的后其他人都可能需要修改配置文件才能正确启动服务这确实很令人烦劳

   最近看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

  这样就可以了



Tags:  dvdspring springfestival spring spring资源文件

延伸阅读

最新评论

发表评论