Issue
Despite there are a lot of discussion around freemarker + spring but it is hard to find neat working example to copy and run.
Could you please provide simplest working configuration of freemarker in spring xml context and java code snippet to load template from resource file and process it.
Solution
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
applicationContext.xml
<bean id="freeMarkerConfigurationFactory" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<property name="templateLoaderPath" value="classpath:/META-INF/freemarker"/>
<property name="preferFileSystemAccess" value="false"/>
</bean>
AlertMailComposer.java
import static org.springframework.ui.freemarker.FreeMarkerTemplateUtils.processTemplateIntoString;
@Component
public class AlertMailComposer implements Processor {
public static final String TEMPLATE = "AlertMail.ftl";
@Autowired
private Configuration freemarkerConfiguration;
protected String composeHtml(Alert alert) throws IOException, TemplateException {
return processTemplateIntoString(freemarkerConfiguration.getTemplate(TEMPLATE), ImmutableMap.of(
"alertType", alert.getAlertType(),
"message", alert.getMessage(),
"nodeName", alert.getEvent().getNodeName(),
"event", toJson(alert.getEvent(), true)
));
}
...
AlertMail.ftl
<html>
<body style="font-family:verdana;font-size:10">
<b>${alertType}: </b>${message}<br>
<b>on: </b>${nodeName}<br>
<p/>
<pre style="font-family:verdana;font-size:10;color:grey">
${event}
</pre>
</body>
</html>
Configuration
class has some interesting properties, like ClassForTemplateLoading
to load resources relative to some class or using basePackagePath. Similar to Class.getResource
.
@Autowired
private FreeMarkerConfigurationFactory freeMarkerConfigurationFactory;
@Bean
public freemarker.template.Configuration negativeRatesFreeMarkerConfiguration() throws IOException, TemplateException {
freemarker.template.Configuration configuration = freeMarkerConfigurationFactory.createConfiguration();
configuration.setClassForTemplateLoading(getClass(), "/" + getClass().getPackage().getName().replace('.', '/'));
return configuration;
}
...
@Resource(name = "negativeRatesFreeMarkerConfiguration")
private Configuration freemarkerConfiguration;
...
freemarkerConfiguration.getTemplate("/service/emailReport.ftl")
Answered By - Mike