freemarker + spring配置和最简单的例子

时间:2015-03-10 09:35:43

标签: java spring freemarker

尽管围绕freemarker + spring进行了很多讨论,但很难找到整齐的工作示例来复制和运行。
能否请你在spring xml上下文中提供最简单的freemarker工作配置和java代码片段,从资源文件中加载模板并进行处理。

4 个答案:

答案 0 :(得分:18)

的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>

答案 1 :(得分:4)

在spring上下文xml中,声明FreemarkerConfigurationFactoryBean就足够了,即

<bean id="freemarkerConfigFactory" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
    <property name="templateLoaderPath" value="classpath:templates/"/>
</bean>

如果使用freemarker.template.Configuration注释,则无需在xml文件中进一步指定@Autowired bean。它由工厂创建并由Spring注入。

答案 2 :(得分:1)

最佳工作示例。您可以下载源代码here

答案 3 :(得分:0)

除了pom.xml中的maven依赖关系,你可以在春天使用java配置 -

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { MyRootContextConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { MyServletContextConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/test/*" };
    } 

}

然后MyRootContextConfig可以

@Bean(name = "myFreeMarkerConfigruation")
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() {
    FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
    bean.setTemplateLoaderPath("classpath:/templates/");
    return bean;
}