我想添加一个完整的答案。
首先,添加依赖项:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6.4</version>
</dependency>
那么,如果你有这样的习惯VelocityEngineFactory
;
@Bean
public VelocityEngineFactory velocityEngine(){
VelocityEngineFactoryBean bean = new VelocityEngineFactoryBean();
Properties properties = new Properties();
properties.setProperty("input.encoding", "UTF-8");
properties.setProperty("output.encoding", "UTF-8");
properties.setProperty("resource.loader", "class");
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
bean.setVelocityProperties(properties);
return bean;
}
您需要将其替换为 bean 定义,如下所示(在您的@Configuration
课程中);下面的定义允许您从类路径加载模板。
@Bean
public VelocityEngine velocityEngine() throws Exception {
Properties properties = new Properties();
properties.setProperty("input.encoding", "UTF-8");
properties.setProperty("output.encoding", "UTF-8");
properties.setProperty("resource.loader", "class");
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine velocityEngine = new VelocityEngine(properties);
return velocityEngine;
}
最后,将其用作:(registration.vm
可在类路径中找到)
@Autowired
private VelocityEngine velocityEngine;
public String prepareRegistrationEmailText(User user) {
VelocityContext context = new VelocityContext();
context.put("username", user.getUsername());
context.put("email", user.getEmail());
StringWriter stringWriter = new StringWriter();
velocityEngine.mergeTemplate("registration.vm", "UTF-8", context, stringWriter);
String text = stringWriter.toString();
return text;
}
祝你好运。