我想使用我尝试过的Apache Freemaker发送电子邮件:
@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配置吗?你能给我一些建议吗?
答案 0 :(得分:1)
问题不是您的Freemarker配置很少,而是两个。请特别注意异常消息的最后一部分:
没有可用的'freemarker.template.Configuration'类型的合格Bean:期望单个匹配的Bean,但找到2 :getFreeMarkerConfiguration,freeMarkerConfiguration
Spring Boot已经带有FreeMarkerAutoConfiguration
。很有可能您还附带了另一个手动定义的代码,您可以验证吗?
请坚持使用application.properties中的Freemarker部分,或者换句话说:使用Spring Boot的spring.freemarker.*
属性来配置应用程序。
答案 1 :(得分:1)
expected single matching bean but found 2: getFreeMarkerConfiguration,freeMarkerConfiguration
当您创建多个同类型的bean,并且只想将其中一个与属性连接时,可能会出现这种情况。在这种情况下,会出现上述错误。 Why this happened?
解决方案1: 使用
@Resource
代替@Autowired
Refer This
解决方案2:使用
@Qualifier
Refer This
解决方案3:使用
@Primaray
Refer This