由于springboot在1.5.x版本開始不支持velocity(https://jira.spring.io/browse/SPR-13235)重父,之后的版本若想使用要自己配置铲咨。
但是由于客觀因素需要族沃,在此簡要記錄我的配置方法辩恼,springboot版本以 2.1.4.RELEASE 為例。
說白了就是缺啥補啥感凤。
1. 指定 spring-boot-starter-velocity 的 maven 配置版本
由于1.5.x后默認不支持鳍寂,所以要手動指定苍在。如下圖:
2. 添加類庫中刪除的文件
由于有關velocity配置以及渲染的類都來源于spring-context-support.jar以及spring-webmvc.jar這兩個包中塘辅。而在這兩個包最新的版本中晃虫,所有有關velocity的類全都刪除了,所以要手動添加相關的類文件扣墩。我這里使用4.3.x的包版本哲银,要添加的包括
- https://github.com/spring-projects/spring-framework/tree/4.3.x/spring-context-support/src/main/java/org/springframework/ui/velocity
-
https://github.com/spring-projects/spring-framework/tree/4.3.x/spring-webmvc/src/main/java/org/springframework/web/servlet/view/velocity
以上兩個路徑下的文件,添加后工程目錄結構如圖:
image.png
然后各種依賴關系以及package的路徑梳理清楚
3. 添加spring.vm并更改路徑
在 https://github.com/spring-projects/spring-framework/tree/4.3.x/spring-webmvc/src/main/resources/org/springframework/web/servlet/view/velocity
路徑下有一個 spring.vm 的模板文件呻惕,由于我們加入的類中啟動用到了這個盘榨,所以需要添加到工程中(其實改一下類文件不要用到也行,但是懶得改了蟆融,加進來就好了)。我添加到了 /resources/templates/ 目錄下守呜。
添加后要注意修改 VelocityConfigurer 類中的 SPRING_MACRO_LIBRARY 常量配置型酥,改為自己添加該文件的路徑山憨。如下圖:
4. 添加自己的 velocity 相關配置
自定義 VelocityConfigurer 和 VelocityViewResolver 并添加為 bean。具體的配置代碼如下:
@Configuration
public class MyVelocityConfig extends WebMvcConfigurerAdapter {
//配置 velocity bean
@SuppressWarnings("deprecation")
@Bean
public VelocityConfigurer velocityConfigurer(ApplicationContext context) {
VelocityConfigurer config = new VelocityConfigurer();
Properties properties = new Properties();
properties.put("input.encoding", "UTF-8");
properties.put("output.encoding", "UTF-8");
config.setVelocityProperties(properties);
return config;
}
//配置 velocity 視圖解析器
@SuppressWarnings("deprecation")
@Bean
public VelocityViewResolver velocityResolver() {
VelocityViewResolver resolver = new VelocityViewResolver();
resolver.setCache(false);
resolver.setPrefix("/templates/");
resolver.setSuffix(".vm");
resolver.setContentType("text/html;charset=UTF-8");
resolver.setExposeSpringMacroHelpers(true);
resolver.setExposeRequestAttributes(true);
//設置RequestContext在視圖頁面中的變量名,以便使用${request}獲取
resolver.setRequestContextAttribute("request");
return resolver;
}
}
也可以將配置寫在專門的配置文件中弥喉,用 setConfigLocation 的方式引入郁竟。
5. 配置完成,寫測試類由境,進行測試棚亩。
結果如圖:
極簡版(只為了velocity測試)的demo已經(jīng)上傳 https://github.com/LiangliangW/velocity
,可以自行取需虏杰。
提醒:這樣強行適配可能產(chǎn)生一定性能問題讥蟆,如并發(fā)量較低,請結合自身業(yè)務取用纺阔,生產(chǎn)環(huán)境一定提前壓測瘸彤。最佳建議還是使用其他更新的模板。