原创

Springboot + Freemarker项目中使用自定义注解

温馨提示:
本文最后更新于 2018年02月07日,已超过 2,231 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

最近在做的项目中使用到了springboot + freemarker的技术,同时项目里多个controller中都需要查询一个公有的数据集合,一般做法是直接在每个controller的方法中通过model.addAttribute("xx", xx);的方式手动设置,但这样就有个明显的问题就是:重复代码!这是不能忍受的。考虑到jsp中的可以使用自定义标签,因此今天尝试了一下在freemarker中使用自定义标签。

1.创建类并实现TemplateDirectiveModel

TemplateDirectiveModel(字面意思:模板指令模型)  

@Component
public class CustomTagDirective implements TemplateDirectiveModel {
    @Autowired
    private RepBankBranchService bankBranchService;
    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        environment.setVariable("listParentBanks", builder.build().wrap(bankBranchService.listParents()));
        templateDirectiveBody.render(environment.getOut());
    }
}

因为这三个列表基本都是同页面显示,因此,就放到一个类中,通过method区分调用。

2.创建Freemarker配置类

@Configuration
public class FreeMarkerConfig {

    @Autowired
    protected freemarker.template.Configuration configuration;
    @Autowired
    protected CustomTagDirective customTagDirective;
    @PostConstruct
    public void setSharedVariable() {
        // icbcTag即为页面上调用的标签名
        configuration.setSharedVariable("icbcTag", customTagDirective);
    }
}

3.ftl中使用自定义的标签

<@icbcTag method="listParentBanks">
    <#if listParentBanks?? && listParentBanks?size gt 0>
        <#list listParentBanks as item>
        <option value="${item.id}">${item.name}</option>
        </#list>
    </#if>
</@icbcTag>

使用方法跟自定义宏(macro)用法一样,直接使用 <@标签名>${值}</@ 标签名  > 即可。

注:ftl中通过@调用自定义标签时,后面可以跟任意参数(由此可以根据具体业务自定义标签)

正文到此结束
本文目录