Freemarker 加载模板方法(SpringBoot环境)
最近项目上用到freeMarker 的模板,遇到有关配置freeMarker的模板路径时,配置过如下情况:**
根据官网上freeMarker的Api配置
但是自己不管怎么修改,还是报freemarker.template.TemplateNotFoundException:
Template not found for name “*.ftl”
1、首先检查下打的包target下是否有你需要的模板文件
没有则需要设置pom文件
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>*.yml</exclude>
<exclude>*.properties</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**
2、JavaBean配置如下(代替xml配置):
@Configuration
public class ApplicationConfig {
@Bean(name = "freeMarkerConfigurer")
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setDefaultEncoding("UTF-8");
configurer.setTemplateLoaderPath("classpath:/ftl");
Map<String, Object> variables = new HashMap<>(1<<1);
variables.put("xml_escape","fmXmlEscape");
configurer.setFreemarkerVariables(variables);
return configurer;
}
}
3、获取模板发送邮件实现类:
@Service
public class sendMailImpl{
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
public void sendMail(){
Configuration configuration = freeMarkerConfigurer.getConfiguration();
Locale locale = new Locale("zh");
Template template = configuration.getTemplate("文件名.ftl",locale,"UTF-8");
}
}
4、需要注意的是必須要把freeMarker 的模板放在配置文件下的resources的文件下,问题解决
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)