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>**/*.ftl</include>
</includes>
</resource>
</resources>
</build>
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 configuration = freeMarkerConfigurer.getConfiguration();
// 加载一个模板文件,创建一个模板对象
Locale locale = new Locale("zh");
Template template = configuration.getTemplate("文件名.ftl",locale,"UTF-8");
//TODO dosome
}
}
4、需要注意的是必須要把freeMarker 的模板放在配置文件下的resources的文件下,问题解决