我想添加一个完整的答案。
首先,添加依赖项:
<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;
}
你需要用一个豆定义来代替它,如下图所示(在你的类中);下面的定义允许您从类路径加载模板。@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;
}
祝你好运。