自由标记+弹簧配置和最简单的示例

2022-09-04 06:50:43

尽管有很多关于freemarker +spring的讨论,但很难找到整洁的工作示例来复制和运行。
你能不能在弹簧xml上下文和java代码片段中提供freemarker的最简单工作配置,以从资源文件加载模板并处理它。


答案 1

啪.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
</dependency>

应用上下文.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类有一些有趣的属性,比如相对于某个类加载资源或使用basePackagePath。似。ClassForTemplateLoadingClass.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")

答案 2

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

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

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


推荐