使用Spring从freemarker获取模板

时间:2010-02-18 09:41:12

标签: spring freemarker

我已经开始查看以下主题 -

Getting template text from FreeMarker in Spring app

我的弹簧配置 -

<bean id="fmConfig" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean"> 
    <property name="templateLoaderPath" value="/WEB-INF/templates"></property> 
</bean>

<bean name="/email.do" class="com.email.web.controller.EmailController">
  <property name="formView" value="email"/>
  <property name="successView" value="email_thanks"/>
  <property name="commandName" value="emailForm"/>
  <property name="commandClass" value="com.email.bean.EmailForm"/>
  <property name="bindOnNewForm" value="true"/>
  <property name="fmConfig" ref="fmConfig"/>
</bean>

将控制器类中的电子邮件正文设为 -

private String makeBody(EmailForm form) {
      StringBuffer content = new StringBuffer(); 

      try { 
          content.append(FreeMarkerTemplateUtils.processTemplateIntoString( 
              fmConfig_.getTemplate("email_default_TM.txt"),form)); 
      } catch (IOException e) {           
      } catch (TemplateException e) { 
      } 
      return content.toString();
    }

在这里,我收到编译器错误“FreeMarkerConfigurationFactoryBean类型的方法getTemplate(String)未定义”。然后我尝试使用fmConfig创建一个Configuration对象 -

try { 
       content.append(FreeMarkerTemplateUtils.processTemplateIntoString( 
       fmConfig_.createConfiguration().getTemplate("email_default_TM.txt"),form)); 
    } catch (IOException e) {           
    } catch (TemplateException e) { 

但是开始获得运行时异常 -

org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/email-a-friend.do' defined in ServletContext resource [/WEB-INF/springapps-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [freemarker.template.Configuration] to required type [org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean] for property 'fmConfig'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [freemarker.template.Configuration] to required type [org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean] for property 'fmConfig': no matching editors or conversion strategy found

我能解决一下吗?感谢。

1 个答案:

答案 0 :(得分:2)

工厂bean应该返回Configuration类型的东西。所以setter应该接受那种类型。

private Configuration fmConfig_;

public void setFmConfig(Configuration fmConfig) {
        fmConfig_ = fmConfig;
    }

以前,我使用FreeMarkerConfigurationFactoryBean而不是配置错误。