springboot引入freemarker最大的问题,在于springboot的application.properties配置文件,不能覆盖所有的freemarker配置
如果freemarker有自定义宏应该怎样引入呢?
首先 application.properties增加配置(与freemarker.properties一样)
auto_import = _
auto_include = /layout/pageShow.html
然后增加FreemarkerConfig类,启动即可
/** * Freemarer 配置 * 增加自动注入和包含配置 * Created by 灰灰 on 2017/7/1. */@org.springframework.context.annotation.Configurationpublic class FreemarkerConfig { private static Logger log = LoggerFactory.getLogger(FreemarkerConfig.class); @Bean public FreeMarkerConfigurer freeMarkerConfigurer(@Value("${auto_import}") String autoImport, @Value("${auto_include}") String autoInclude) { FreeMarkerConfigurer config = new FreeMarkerConfigurer(); writerProperties(config); Configuration configuration = null; try { configuration = config.createConfiguration(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } setAutoImport(autoImport,configuration); setAutoInclude(autoInclude,configuration); config.setConfiguration(configuration); return config; } @Autowired private FreeMarkerProperties properties; private void writerProperties(FreeMarkerConfigurer config) { config.setTemplateLoaderPaths(this.properties.getTemplateLoaderPath()); config.setPreferFileSystemAccess(this.properties.isPreferFileSystemAccess()); config.setDefaultEncoding(this.properties.getCharsetName()); Properties settings = new Properties(); settings.putAll(this.properties.getSettings()); config.setFreemarkerSettings(settings); } private void setAutoImport(String autoImport,Configuration configuration) { if("_".equals(autoImport.trim())) { return; } String[] imports = autoImport.split(";"); Map<String,String> importMap = new HashMap<String,String>(imports.length); for (String s : imports) { String[] keyValue = s.split("as"); if (keyValue.length != 2) { log.error("freemarker配置auto_import格式不正确 "); throw new RuntimeException("freemarker配置auto_import格式不正确"); } importMap.put(keyValue[1].trim(),keyValue[0].trim()); } configuration.setAutoImports(importMap); } private void setAutoInclude(final String autoInclude,Configuration configuration) { if ("_".equals(autoInclude.trim())) { return; } String[] includes = autoInclude.split(";"); for (String s : includes) { System.out.println(s); } List list = new ArrayList<String>(Arrays.asList(includes)); configuration.setAutoIncludes(list); }}
原文地址:https://www.cnblogs.com/rock-turf/p/11108006.html
时间: 2024-11-07 18:52:53