通过字段 'freemarkerConfig' 表示的未满足的依赖关系

Unsatisfied dependency expressed through field 'freemarkerConfig'

我想使用 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 配置?你能给我一些建议吗?

问题不在于你需要几个 Freemarker 配置,而是两个太多。特别注意异常信息的最后一部分:

No qualifying bean of type 'freemarker.template.Configuration' available: expected single matching bean but found 2: getFreeMarkerConfiguration,freeMarkerConfiguration

Spring 引导已经带有 FreeMarkerAutoConfiguration。很可能你附带了另一个你手动定义的,你能验证一下吗?

请坚持使用 application.properties 中的 Freemarker 部分,或者换句话说:使用 Spring Boot.

spring.freemarker.* 属性配置您的应用程序
expected single matching bean but found 2: getFreeMarkerConfiguration,freeMarkerConfiguration

可能会出现这样一种情况,当您创建多个相同类型的 bean 并且只想使用 属性 连接其中一个时。在这种情况下,会出现上述错误。


Solution 1: Use @Resource instead of @Autowired Refer This


Solution 2: Use @Qualifier Refer This


Solution 3: Use @Primaray Refer This