TemplateProcessingService.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package com.yango.javaailangchain4j.service;
  2. import freemarker.template.Configuration;
  3. import freemarker.template.Template;
  4. import freemarker.template.TemplateException;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
  9. import java.io.IOException;
  10. import java.util.Map;
  11. @Service
  12. public class TemplateProcessingService {
  13. @Autowired
  14. @Qualifier("customFreeMarkerConfiguration")
  15. private Configuration freemarkerConfig;
  16. /**
  17. * 使用FreeMarker模板引擎处理模板字符串
  18. *
  19. * @param templateString 模板字符串
  20. * @param templateData 模板数据
  21. * @param templateName 模板名称,用于调试
  22. * @return 处理后的字符串
  23. * @throws IOException IO异常
  24. * @throws TemplateException 模板异常
  25. */
  26. public String processTemplate(String templateString, Map<String, Object> templateData, String templateName)
  27. throws IOException, TemplateException {
  28. Template template = new Template(templateName, templateString, freemarkerConfig);
  29. return FreeMarkerTemplateUtils.processTemplateIntoString(template, templateData);
  30. }
  31. /**
  32. * 使用FreeMarker模板引擎处理模板字符串(使用默认模板名称)
  33. *
  34. * @param templateString 模板字符串
  35. * @param templateData 模板数据
  36. * @return 处理后的字符串
  37. * @throws IOException IO异常
  38. * @throws TemplateException 模板异常
  39. */
  40. public String processTemplate(String templateString, Map<String, Object> templateData)
  41. throws IOException, TemplateException {
  42. return processTemplate(templateString, templateData, "defaultTemplate");
  43. }
  44. }