1、配置configure的Bean,Bean中指定了模板文件的路径和刷新时间等配置。
<!-- 配置freeMarkerConfigurer进行属性值的注入 --> <bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPaths" value="classpath:SMSTemplate" /> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">1800</prop><!-- 模板更新延时 --> <prop key="default_encoding">UTF-8</prop> <prop key="locale">zh_CN</prop> </props> </property> </bean>
2、定义模板文件。
<#compress> 实时气象信息:风向为在${weatherInfo.windDir!},<#rt> ${weatherInfo.windPower!}。<#rt> 今日${weatherInfo.stateDetailed!},<#rt> 最高温度${weatherInfo.tem1!}<#rt> 。<#rt> </#compress>
3、模板+数据=实际需要的内容
@Component public class FreeMarkService { private Log logger = LogFactory.getLog(FreeMarkService.class); @Autowired private FreeMarkerConfigurer freeMarkerConfigurer; /** * 传入weatherInfo得到天气短信的模板 * @param weatherInfo * @return */ public String generateSmsByWeatherInfo(WeatherInfo weatherInfo) { String retSmsContent = ""; Template tpl = null; try { Map<String, Object> root = new HashMap<String, Object>(); root.put("weatherInfo", weatherInfo); tpl = freeMarkerConfigurer.getConfiguration().getTemplate("weather.ftl"); retSmsContent = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, root); } catch (Exception e) { // TODO: handle exception logger.error("生成天气短信内容错误。"+e.getMessage()); } return retSmsContent; } }
时间: 2024-10-29 03:39:38