我想使用Apache Freemarker发送电子邮件我试过这个:
@Service
public class EMailSender {
@Autowired
private Configuration freemarkerConfig;
public void sendMail(String to, String subject, String content) {
try { freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates");
EmailRegistrationModel obj = new EmailRegistrationModel();
obj.setMailSubject("Test");
Map<String, Object> model = new HashMap<String, Object>();
model.put("title", "Some name");
obj.setModel(model);
String data = geFreeMarkerTemplateContent(model);
helper.setText(data, true);
mailSender.send(message);
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
private String geFreeMarkerTemplateContent(Map<String, Object> model){
StringBuffer content = new StringBuffer();
try{
content.append(FreeMarkerTemplateUtils.processTemplateIntoString(
freemarkerConfig.getTemplate("emails_activate.html"), model));
return content.toString();
}catch(Exception e){
System.out.println("Exception occured while processing fmtemplate:"+e.getMessage());
}
return "";
}
}
配置对象:
public class EmailRegistrationModel {
private String mailContent;
private Map<String, Object> model;
....
}
当我部署代码时,我得到:
Error creating bean with name 'EMailSender': Unsatisfied dependency expressed through field 'freemarkerConfig'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'freemarker.template.Configuration' available: expected single matching bean but found 2: getFreeMarkerConfiguration,freeMarkerConfiguration
你知道我怎么解决这个问题吗?我想我需要添加一些freemarker配置?你能给我一些建议吗?
问题不在于你需要很少的Freemarker配置而是两个。特别注意异常消息的最后部分:
没有'freemarker.template.Configuration'类型的限定bean可用:期望的单个匹配bean但找到2:getFreeMarkerConfiguration,freeMarkerConfiguration
Spring Boot已经附带了FreeMarkerAutoConfiguration
。很可能你带来了另一个你手动定义的,你能验证一下吗?
请坚持使用application.properties中的Freemarker部分,或者换句话说:使用Spring Boot的spring.freemarker.*
属性配置应用程序。
expected single matching bean but found 2: getFreeMarkerConfiguration,freeMarkerConfiguration
当您创建多个相同类型的bean并且只想使用属性连接其中一个bean时,可能会出现这种情况。在这种情况下,会出现上述错误。 Why this happened?
解决方案1:使用
@Resource
而不是@Autowired
Refer This
解决方案2:使用
@Qualifier
Refer This
解决方案3:使用
@Primaray
Refer This