您的位置:首页 > 编程语言 > Java开发

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

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

1.创建类并实现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中通过@调用自定义标签时,后面可以跟任意参数(由此可以根据具体业务自定义标签)

Springboot + Freemarker项目中使用自定义注解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息