Velocity 在 Spring Boot 中找不到模板资源

问题描述 投票:0回答:1

我正在使用 Velocity 模板引擎在我的 Spring boot 应用程序中使用电子邮件模板发送电子邮件实用程序。

当前代码如下所示。

pom.xml:

    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity</artifactId>
        <version>1.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-tools</artifactId>
        <version>2.0</version>
    </dependency>

速度引擎 bean 配置:

@Configuration
public class VelocityConfig {

@Bean
public VelocityEngine velocityEngine() {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();
    return ve;
  }
}

电子邮件模板放置在

src/main/resources/email-templates/summary-email.vm

<!DOCTYPE html>
<head>
  <title>Summary</title>
</head>
<body>
   <h1>Claims Summary</h1>
</body>
</html>

放置在以下目录中:

src
├── main
│   ├── java
│   │   └── com
│   │       └── packageNameioot
│   │           └── SpringBootApplication.java
│   ├── resources
│   │   ├── email-templates
│   │   │   └── summary-email.vm
│   │   └── application.properties

使用模板发送电子邮件的服务类:

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailSummaryService {

  private final EmailConnector connector;
  private final VelocityEngine velocityEngine;

  public Mono<Void> sendFinanceClaimsRunEmailSummary(FinancePeriodRunEntity periodRunEntity, int successCount, int errorCount) {
    EmailDto emailDto = EmailDto.builder()
                                .recipients(Set.of("[email protected]"))
                                .subject("Claims summary")
                                .body(createEmailBody())
                                .html(true)
                                .build();
    return connector.submitEmailRequest(emailDto);
 }

  private String createEmailBody() {
    VelocityContext context = new VelocityContext();
    Template template = velocityEngine.getTemplate("email-templates/summary-email.vm");
    StringWriter writer = new StringWriter();
    template.merge(context, writer);
    return writer.toString();
  }
}

但是Velocity无法定位模板,出现以下错误。

ERROR velocity:96 - ResourceManager : unable to find resource 'email-templates/summary-email.vm' in any resource loader.
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'email-templates/summary-email.vm'
java spring-boot apache-velocity
1个回答
0
投票

属性应该这样设置:

    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("resource.loader.classpath.class",
                   ClasspathResourceLoader.class.getName());

根据 Apache Velocity Engine 文档

© www.soinside.com 2019 - 2024. All rights reserved.