package com.yango.javaailangchain4j.service; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import java.io.IOException; import java.util.Map; @Service public class TemplateProcessingService { @Autowired @Qualifier("customFreeMarkerConfiguration") private Configuration freemarkerConfig; /** * 使用FreeMarker模板引擎处理模板字符串 * * @param templateString 模板字符串 * @param templateData 模板数据 * @param templateName 模板名称,用于调试 * @return 处理后的字符串 * @throws IOException IO异常 * @throws TemplateException 模板异常 */ public String processTemplate(String templateString, Map templateData, String templateName) throws IOException, TemplateException { Template template = new Template(templateName, templateString, freemarkerConfig); return FreeMarkerTemplateUtils.processTemplateIntoString(template, templateData); } /** * 使用FreeMarker模板引擎处理模板字符串(使用默认模板名称) * * @param templateString 模板字符串 * @param templateData 模板数据 * @return 处理后的字符串 * @throws IOException IO异常 * @throws TemplateException 模板异常 */ public String processTemplate(String templateString, Map templateData) throws IOException, TemplateException { return processTemplate(templateString, templateData, "defaultTemplate"); } }