Search code examples
javaspringspring-bootfreemarker

Unsatisfied dependency expressed through field 'freemarkerConfig'


I want to send e-mails using Apache Freemaker I tried this:

@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 "";
    }
}

Object for configuration:

public class EmailRegistrationModel {       
    private String mailContent;     
    private Map<String, Object> model;
    ....
}

When I deploy the code I get:

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

Do you know how I can solve this issue? I suppose that I need to add some freemarker configuration? Can you give me some advice?


Solution

  • The problem is not that you have to few Freemarker configs but two much. Pay special attention to the last part of the exception message:

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

    Spring Boot already comes with a FreeMarkerAutoConfiguration. Most probably you come with another one which you defined manually, could you verify this?

    Please stick to the Freemarker section in the application.properties or in other words: configure you application with the spring.freemarker.* properties of Spring Boot.