目前
Spring Boot
允许使用 Thymeleaf
属性为 spring.thymeleaf.prefix
模板位置指定一个值。
默认值为
。classpath:/templates/
我想为 thymeleaf 模板设置另一个位置(但保留默认位置),在 jar 之外,例如:
spring.thymeleaf.prefix = classpath:/templates/, file:/resources/templates
我是否必须为我想要的新位置定义另一个模板解析器?
在
application.properties
文件中定义设置
spring.thymeleaf.templateResolverOrder=1
现在在创建 ITemplateResolver 的自定义 Bean 中将顺序以及前缀和后缀设置为 0。这样 Spring Boot 就会监听这两个地方
将 order 设置为 0 很重要
创建 bean 的示例可以是
@Bean
public ClassLoaderTemplateResolver emailTemplateResolver() {
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("mails/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode(TemplateMode.HTML);
emailTemplateResolver.setCharacterEncoding("UTF-8");
emailTemplateResolver.setOrder(0);
emailTemplateResolver.setCheckExistence(true);
return emailTemplateResolver;
}
为了定义多个模板位置,您必须定义实现 ITemplateResolver 的 Spring beans。
@Bean
public SpringResourceTemplateResolver firstTemplateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("classpath:/templates/templatelocation/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setOrder(0);
templateResolver.setCheckExistence(true);
return templateResolver;
}
@Bean
public ClassLoaderTemplateResolver secondTemplateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("templates/templatelocation/other/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setOrder(1);
templateResolver.setCheckExistence(true);
return templateResolver;
}
您还可以查看详细介绍用法的博客文章。