springboot整合freemarker自动加载宏
Posted rock-turf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot整合freemarker自动加载宏相关的知识,希望对你有一定的参考价值。
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.Configuration
public 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);
以上是关于springboot整合freemarker自动加载宏的主要内容,如果未能解决你的问题,请参考以下文章