sndu
sndu

Reputation: 1033

unable to autowire TemplateEngine in thymeleaf?

This is my code which I use to send a html email using java spring and thymeleaf template engine.

@Service
public class EmailServiceImpl implements EmailService {
    private static final String EMAIL_SIMPLE_TEMPLATE_NAME = "html/html";
@Value("${email.user.register.body}")
private String USER_REGISTER_MESSAGE_BODY;

@Value("${email.user.register.subject}")
private String USER_REGISTER_MESSAGE_SUBJECT;

@Value("${mailSender.address}")
private String SENDER_EMAIL_ADDRESS;

@Autowired
private JavaMailSender mailSender;

@Autowired
private TemplateEngine templateEngine;

@Override
public void sendEmail(MimeMessagePreparator preparator) {
    mailSender.send(preparator);
}

@Async
@Override
public void sendUserRegisterEmail(String receiver, String receiverEmailAddress){
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setSubject(USER_REGISTER_MESSAGE_SUBJECT);
            message.setTo(receiverEmailAddress);
            message.setFrom(SENDER_EMAIL_ADDRESS);
            message.setText(String.format(USER_REGISTER_MESSAGE_BODY, receiver));
        }
    };
    sendEmail(preparator);
}

public void sendMailWithInline(
        final String recipientName, final String recipientEmail, final String imageResourceName,
        final byte[] imageBytes, final String imageContentType, final Locale locale)
        throws MessagingException {

    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
    ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message =
            new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
    message.setSubject("Example HTML email with inline image");
    message.setFrom("[email protected]");
    message.setTo(recipientEmail);

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process(EMAIL_SIMPLE_TEMPLATE_NAME, ctx);
    message.setText(htmlContent, true); // true = isHtml

    // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
    final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
    message.addInline(imageResourceName, imageSource, imageContentType);

    // Send mail
    this.mailSender.send(mimeMessage);

}

I am getting the following error while trying to run it using Jetty and Intellij idea.

    [WARNING] Failed startup of context o.e.j.m.p.JettyWebAppContext@23321be7{/adsops,file:///E:/Projects/ADpost/ops/dev/src/main/webapp/,STARTING}{file:///E:/Projects/ADpost/ops/dev/src/main/webapp/}
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationUserServiceImpl': Unsatisfied dependency expressed through field 'emailService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emailServiceImpl': Unsatisfied dependency expressed through field 'templateEngine'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'templateEngine' defined in com.vlclabs.adsops.configuration.WebApplicationConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.thymeleaf.spring4.SpringTemplateEngine]: Factory method 'templateEngine' threw exception; nested exception is java.lang.NoClassDefFoundError: org/thymeleaf/dialect/IExpressionEnhancingDialect

These are the dependencies

  <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>${thymeleaf.version}</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-conditionalcomments</artifactId>
        <version>${thymeleaf-extras-conditionalcomments.version}</version>
    </dependency>

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
        <version>${thymeleaf-extras-java8time.version}</version>
    </dependency>

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>${thymeleaf-extras-springsecurity4.version}</version>
    </dependency>

While trying to go through the error message I understand the error may occur due to mistake I did while adding template engine. However I couldn't fix it trying for days. Please help

Upvotes: 0

Views: 2423

Answers (1)

holmis83
holmis83

Reputation: 16644

The problem is likely that you mix versions that are not compatible. You can check your versions by running:

mvn dependency:tree

(If you have Eclipse, you can open the pom file and switch to "Dependency Hierarchy" tab for the same thing.)

Especially check for these:

  • org.thymeleaf:thymeleaf-spring4:jar
  • org.thymeleaf:thymeleaf:jar

These two should have the same version. If they don't, adjust your dependencies.

Upvotes: 2

Related Questions