问答详情
源自:5-1 课程总结

自定义配置文件如何配置

自定义指令是,再springboot中,如何配置key指令文件?

提问者:慕先生5357798 2018-07-12 17:30

个回答

  • A未来战士N
    2018-12-28 16:32:34

    @Component
    public class RoleDirectiveModel implements TemplateDirectiveModel {
        /**
         *
         * @param environment 环境变量
         * @param params 指令参数(存储你所需要的值,随便是什么Key-Value你懂的)
         * @param loopVars 循环变量 返回值
         * @param templateDirectiveBody 指令内容
         * 除了params外,其他的都能是Null。
         * @throws TemplateException
         * @throws IOException
         */
        @Override
        public void execute(Environment environment, Map params, TemplateModel[] loopVars, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
            System.out.println("=========");
            TemplateScalarModel user=(TemplateScalarModel)params.get("user");
            TemplateScalarModel role=(TemplateScalarModel)params.get("role");
    
            if("123456".equals(user.getAsString()) && "admin".equals(role.getAsString()) ){
                loopVars[0]=TemplateBooleanModel.TRUE;
            }
    
            List<String> otherRights=new ArrayList<>();
            otherRights.add("add");
            otherRights.add("update");
            otherRights.add("delete");
            loopVars[1]=new SimpleSequence(otherRights);
    
            templateDirectiveBody.render(environment.getOut());
        }
    }

    这是自定义指令的定义类


    这是加载自定义指令的freemarker java配置类

    import com.example.demo.model.tag.RoleDirectiveModel;
    import com.example.demo.model.tag.SortMethod;
    import freemarker.template.TemplateModelException;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    
    import javax.annotation.PostConstruct;
    
    @Slf4j
    @Configuration
    public class FreeMarkerAutoConfiguration {
    
        @Autowired
        private freemarker.template.Configuration configuration;
        @Autowired
        private RoleDirectiveModel roleDirectiveModel;
        @Autowired
        private SortMethod sortMethod;
    
        @PostConstruct
        public void setSharedVariable() {
            try {
                //自定义标签
                configuration.setSharedVariable("role", roleDirectiveModel);
                configuration.setSharedVariable("sort_int",sortMethod);
            } catch (Exception e) {
                log.error("Custom tags failed to load:{}", e.getMessage());
            }
        }
    }