简体   繁体   中英

Spring Mail with Freemarker Templates from Database

I am a newbie to adding Freemarker to Spring and Spring Mail. I am not using Spring Boot, but I am using the latest Spring 4.x, and though we have an application context XML file, we do use annotations.

So, ultimately I want to read the templates out of a database, because we may have many of them for many clients. We will not be loading templates from a filename or from disk.

We have our Spring Application as a maven multi-module project:

entity.jar - module
dao.jar - module
services.jar - module
ws.jar - module

Under services we have an application context file that defines Freemarker as follow:

 <bean id="freemarkerConfiguration"
        class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
        <property name="preTemplateLoaders">
            <list>
                <ref bean="databaseTemplateLoader" />
            </list>
        </property>
      </bean>

      <bean name="databaseTemplateLoader" 
       class="com.myapp.server.util.DatabaseToFreeMarkerTemplateLoader" />

I have a new class called:

  public class DatabaseToFreeMarkerTemplateLoader extends StringTemplateLoader
     {
        // todo: add code here
     }

But I am not sure what else I need in here. I am looking on the internet for some examples, but I can't find too much.

If someone can point me to an example, or refer me to another link here, I'll do my best to see if I can literally fill in the blanks.

Thanks!

BTW: I am surprised I had to include spring-web in my services layer in order to make this work. I just wanted to format an email and not html pages. So if there a better formatting tool that works seamlessly with Spring, let me know.

I don't know this part of Spring much, but I don't think you need spring-web . You could just use the FreeMarker API directly both for configuring (ie, create a freemarker.template.Configuration singleton bean) and generating the output ( template = configuration.getTemplate(...) , template.process(...) ). Finally you simply use message.setText(theOutputFromTemplateDotProcess, true); (where message is the Spring MimeMessageHelper ). So there's no much to integrate with Spring here, I believe. (Even if someone needs to load templates from Spring resources, they can use an org.springframework.ui.freemarker.SpringTemplateLoader via Configuration.setTemplateLoader .)

As of using FreeMarker API directly (not related to Spring), see this example: http://freemarker.org/docs/pgui_quickstart_all.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM