FreeMarker注入静态方法,以及在IDEA中获取代码编写提示
前言
- springbootWeb项目
- 项目中引入的Hutool5.8.x版本工具类。
FreeMarker注入全局变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| @Slf4j public class FreemarkerConfig {
public static void init() {
Configuration c = SpringUtil.getBean(Configuration.class); BeansWrapperBuilder beansWrapperBuilder = new BeansWrapperBuilder(c.getIncompatibleImprovements()); BeansWrapper wrapper = beansWrapperBuilder.build(); TemplateHashModel staticModels = wrapper.getStaticModels(); try { TemplateHashModel dateUtil = (TemplateHashModel) staticModels.get(DateUtil.class.getName()); c.setSharedVariable("dateUtil", dateUtil); c.setNumberFormat("#.########"); c.setCustomNumberFormats(MapUtil.of("amt", AmtTemplateNumberFormatFactory.INSTANCE)); c.setDateTimeFormat(DatePattern.NORM_DATETIME_PATTERN); c.setDateFormat(DatePattern.NORM_DATE_PATTERN); c.setTimeFormat(DatePattern.NORM_TIME_PATTERN); c.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); } catch (Exception e) { log.error("FreeMarker全局变量注入失败!", e); } } }
|
自定义数字格式化
AmtTemplateNumberFormatFactory.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| public class AmtTemplateNumberFormatFactory extends TemplateNumberFormatFactory {
public static final AmtTemplateNumberFormatFactory INSTANCE = new AmtTemplateNumberFormatFactory();
private AmtTemplateNumberFormatFactory() { }
@Override public TemplateNumberFormat get(String params, Locale locale, Environment env) throws InvalidFormatParametersException { TemplateFormatUtil.checkHasNoParameters(params); return HexTemplateNumberFormat.INSTANCE; }
private static class HexTemplateNumberFormat extends TemplateNumberFormat {
private static final HexTemplateNumberFormat INSTANCE = new HexTemplateNumberFormat();
private HexTemplateNumberFormat() { }
@Override public String formatToPlainText(TemplateNumberModel numberModel) throws UnformattableValueException, TemplateModelException { Number n = TemplateFormatUtil.getNonNullNumber(numberModel); try { return cn.hutool.core.util.NumberUtil.decimalFormat("#.00####", n); } catch (ArithmeticException e) { throw new UnformattableValueException(n + " 不适合金额"); } }
@Override public boolean isLocaleBound() { return false; }
@Override public String getDescription() { return "金额格式化"; }
}
}
|
IDEA中获取代码编写提示
在templates
文件夹下新建freemarker_implicit.ftl
文件
1 2 3 4
| [#ftl] [#-- @implicitly included --] [#-- @ftlvariable name="dateUtil" type="cn.hutool.core.date.DateUtil.static" --] [#--说明,此文件主要用于IDEA代码提示,存在或不存在不影响实际功能--]
|
新建项目启动后执行钩子让配置生效
新建PostRunner.java
文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
@Component public class PostRunner implements CommandLineRunner {
@Override public void run(String... args) { FreemarkerConfig.init(); } }
|