如何访问我的freemarker模板(* .ftl)文件从我的代码(春季启动应用程序)存储在我的src / main /资源文件夹中?
我尝试以下
freemarker.template.Configuration config = new Configuration();
configuration.setClassForTemplateLoading(this.getClass(), "/resources/templates/");
并且收到以下异常
freemarker.template.TemplateNotFoundException: Template not found for name "my-template.ftl".
类路径的根是src/main/resources
,改变路径
configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
我正面临“freemarker.template.TemplateNotFoundException:找不到名称模板...”的问题。我的代码是正确的,但我忘了,包括在pom.xml中/模板/目录。所以,下面的代码固定我的问题。我希望这有帮助。
AppConfig.java :
@Bean(name="freemarkerConfiguration")
public freemarker.template.Configuration getFreeMarkerConfiguration() {
freemarker.template.Configuration config = new freemarker.template.Configuration(freemarker.template.Configuration.getVersion());
config.setClassForTemplateLoading(this.getClass(), "/templates/");
return config;
}
EmailSenderServiceImpl.java:
@Service("emailService")
public class EmailSenderServiceImpl implements EmailSenderService
{
@Autowired
private Configuration freemarkerConfiguration;
public String geFreeMarkerTemplateContent(Map<String, Object> dataModel, String templateName)
{
StringBuffer content = new StringBuffer();
try {
content.append(FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate(templateName), dataModel));
return content.toString();
}
catch(Exception exception) {
logger.error("Exception occured while processing freeMarker template: {} ", exception.getMessage(), exception);
}
return "";
}
}
pom.xml :
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources/</directory>
<includes>
<include>templates/*.ftl</include>
</includes>
</resource>
<resource>
<directory>src/main/</directory>
<includes>
<include>templates/*.ftl</include>
</includes>
</resource>
</resources>
</build>