springboot加载远程freemarker模板ftl
解决方法:
1、springboot启动类继承以下类:
package com.bx.common;
import com.bx.common.conf.MyFreemarkerView;
import freemarker.template.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import java.util.*;
public class BaseApplication {
@Autowired
private Environment env;
@Autowired
private FreeMarkerProperties fmkProp;
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return null;
}
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer factory = new FreeMarkerConfigurer();
factory.setTemplateLoaderPaths(this.fmkProp.getTemplateLoaderPath());
factory.setPreferFileSystemAccess(this.fmkProp.isPreferFileSystemAccess());
factory.setDefaultEncoding(this.fmkProp.getCharsetName());
Properties settings = new Properties();
settings.putAll(this.fmkProp.getSettings());
factory.setFreemarkerSettings(settings);
Configuration configuration = null;
try {
configuration = factory.createConfiguration();
// configuration.setAutoImports(new HashMap());
String path=this.env.getProperty("spring.freemarker.template-loader-path");
//加载远程的ftl文件路径
configuration.setTemplateLoader(new RemoteTemplateLoader(path));
} catch (Exception var4) {
var4.printStackTrace();
}
factory.setConfiguration(configuration);
return factory;
}
@Bean
public CommandLineRunner customFreemarker(final FreeMarkerViewResolver resolver) {
return new CommandLineRunner() {
public void run(String... strings) throws Exception {
resolver.setViewClass(MyFreemarkerView.class);
}
};
}
}
2、MyFreemarkerView类
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public class MyFreemarkerView extends FreeMarkerView {
public MyFreemarkerView() {
}
protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws
Exception {
model.put("yml", "全局变量,可以在ftl中使用");
super.exposeHelpers(model, request);
}
}
3、application.yml配置
spring:
freemarker:
cache: false
template-loader-path: http://localhost:18080/