簡體   English   中英

在Spring Context中檢索速度的郵件模板時出錯

[英]Error retrieving mail template for Velocity in Spring Context

我在Spring遇到VelocityEngine的問題,我的任務是檢索郵件模板。

這是我的配置:

SPRING-CONTEXT.xml:

<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
    <property name="velocityProperties">
        <value>
            resource.loader=file
            file.resource.loader.class=org.apache.velocity.runtime.resource.loader.FileResourceLoader
            file.resource.loader.path=${template.path}
            file.resource.loader.cache=${template.cache}
            file.resource.loader.modificationCheckInterval=${template.modificationCheckInterval}
        </value>
    </property>
</bean>

JAVA:

@Autowired
private JavaMailSender javaMailSender;  

@Autowired
private VelocityEngine velocityEngine;

public void sendEMailFromTemplate(String to, String subject, String template, Object object) {
    MimeMessagePreparator mmp = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setFrom(mailFrom);
            message.setTo(to);
            message.setSubject(subject);
            Map<String,Object> model = new HashMap<String,Object>();
            model.put("object", object);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, StandardCharsets.UTF_8.name(), model);
            message.setText(text, true);
        }
    };
    this.javaMailSender.send(mmp);
}

在應用執行方法“發送”時出現的錯誤下方:

org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler handleUncaughtException - Unexpected error occurred invoking async method 'public void test.EMailService.sendEMailFromTemplate(java.lang.String,java.lang.String,java.lang.String,java.lang.Object)'.
org.springframework.mail.MailPreparationException: Could not prepare mail; nested exception is org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'email.vm'
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:371)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:350)
    at test.EMailService.sendEMailFromTemplate(EMailService.java:44)
    at test.EMailService$$FastClassBySpringCGLIB$$f6dc0165.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:108)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'email.vm'
    at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
    at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
    at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
    at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:343)
    at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplate(VelocityEngineUtils.java:71)
    at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplateIntoString(VelocityEngineUtils.java:112)
    at test.EMailService$1.prepare(MailService.java:41)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
    ... 9 more

怎么了? 謝謝。

嘗試這個

在您的applicationContext.xml中

     <bean id="velocityEngine"
        class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="velocityProperties">
            <value>
                resource.loader=class       

                class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
            </value>
        </property>
     </bean>


    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
        <list>
          <value>classpath:velocity.properties</value>
       </list>
      </property>
   </bean>

在你的velocity.properties中

  velocity.createAccountVerificationEmailSubject=your subject
  velocity.createAccountVerificationEmailTemplate=yourTemplate.vm

為您服務

@Autowired
  private VelocityEngine velocityEngine;

  @Value("${velocity.createAccountVerificationEmailSubject}")
  private String createAccountVerificationEmailSubject;

  @Value("${velocity.createAccountVerificationEmailTemplate}")
  private String createAccountVerificationEmailTemplate;

  @Override
  public void sendCreateAccountVerificationEmail(User user) {
    Email email = new Email();//create an Email object
    email.setTo(user.getEmail());
    email.setSubject(createAccountVerificationEmailSubject);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(CREATE_ACCOUNT_VERIFICATION_TOKEN_KEY, user.getToken());
    email.setContent(createMessageText(createAccountVerificationEmailTemplate, params));
    sendEmail(email);
  }

  public void sendEmail(final Email email) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
      public void prepare(MimeMessage mimeMessage) throws Exception {
        mimeMessage.addRecipients(Message.RecipientType.TO, email.getTo());
        mimeMessage.setSubject(email.getSubject());
        mimeMessage.setSentDate(new Date());
        mimeMessage.setFrom(new InternetAddress("yourFrom"));
        InternetAddress internetAddress = new InternetAddress(email.getFrom());
        internetAddress.setPersonal(email.getFromHeader());
        mimeMessage.setFrom(internetAddress);
        mimeMessage.setText(email.getContent(), CHARSET, MIME_SUBTYPE);
      }
    };

    try {
      mailSender.send(preparator);
    } catch (MailException ex) {
      log.error(ex.getMessage());
    }
  }


  private String createMessageText(String templateName, Map<String, Object> model)   {
    String result = null;
    try {
      result =
          VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
              templateName, model);
    } catch (VelocityException e) {
      log.error(e.getMessage());
    }
    return result;
  }

希望能幫助到你!

問題是在此屬性中設置的值:

file.resource.loader.path = $ {template.path}

“ template.path”屬性設置了帶有“ \\”字符分隔符的路徑,因此Spring擦除了所有字符分隔符,從而避免了正確的路徑。 我用“ /”代替“ \\”解決了這個問題。

無論如何謝謝你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM