<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="classpath:com/byd/cmms/mailTpl"/><!--指定模板文件目录-->
<property name="freemarkerSettings"><!-- 设置FreeMarker环境属性-->
<props>
<prop key="template_update_delay">1800</prop><!--刷新模板的周期,单位为秒-->
<prop key="default_encoding">UTF-8</prop><!--模板的编码格式 -->
<prop key="locale">zh_CN</prop><!-- 本地化设置-->
</props>
</property>
</bean>
@Service
@Transactional
public class EmailService implements IEmailService{
private Log log = LogFactory.getLog(this.getClass().getName());
@Resource
private FreeMarkerConfigurer freeMarkerConfigurer;
public String getMailText(Map map){
String htmlText="";
try {
//通过指定模板名获取FreeMarker模板实例
Template tpl=freeMarkerConfigurer.getConfiguration().getTemplate((String)map.get(IEmailService.MAIL_TPL));
//解析模板并替换动态数据
htmlText=FreeMarkerTemplateUtils.processTemplateIntoString(tpl,map);
} catch (Exception e) {
log.error("getMailText(map) getTemplate failure!", e);
}
return htmlText;
}
@Override
public void mail(Map map) {
String mailToAddress = (String)map.get(IEmailService.MAIL_TOADDRESS);
String subject = (String)map.get(IEmailService.MAIL_SUBJECT);;
String content = getMailText(map);
MailUtils.mail(mailToAddress, subject, content);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class T1ServiceTest extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
private IEmailService templateEmailService;
@Test
public void testGetT1() {
Map map = new HashMap();
map.put(IEmailService.MAIL_TPL, "test.tpl");
map.put("username","小明");
System.out.println("---------------------------------");
System.out.println(templateEmailService.getMailText(map));
System.out.println("---------------------------------");
}
}
spring.jar+freemarker.jar