码迷,mamicode.com
首页 > 编程语言 > 详细

springboot整合freemarker自动加载宏

时间:2019-06-29 22:06:30      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:run   gets   ogg   loader   files   str   new   exception   this   

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自动加载宏

标签:run   gets   ogg   loader   files   str   new   exception   this   

原文地址:https://www.cnblogs.com/rock-turf/p/11108006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!