我们业务有JF模板放在数据库的,修改时也会更新,刚看到社区有社友问类似的需求 https://jfinal.com/feedback/8396。
简单的剔除一下我们业务代码,留下工具代码,供参考改造,废话不多说了,上石马!
import com.jfinal.template.source.ISource; public class UpdateSource implements ISource { private boolean isModified = false; private StringBuilder content; public UpdateSource(StringBuilder content) { this.content = content; } public void updateContent(StringBuilder content) { isModified = true; this.content = content; } @Override public boolean isModified() { return isModified; } @Override public String getCacheKey() { return null; } @Override public StringBuilder getContent() { isModified = false; return content; } @Override public String getEncoding() { return null; } }
管理工具类:
import com.jfinal.render.RenderManager; import com.jfinal.template.Engine; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class EngineSharedFunctionKit { private final Map<String, UpdateSource> MAP = new ConcurrentHashMap<>(); private final Engine engine; private static EngineSharedFunctionKit web; public synchronized static EngineSharedFunctionKit web() { if (web == null){ web = new EngineSharedFunctionKit(getWebEngine()); } return web; } public static Engine getWebEngine() { return RenderManager.me().getEngine(); } public EngineSharedFunctionKit(Engine engine) { this.engine = engine; engine.setDevMode(true); } public void put(String key, String value) { put(key, new StringBuilder(value)); } public synchronized void put(String key, StringBuilder value) { UpdateSource source = MAP.get(key); if (source != null) { source.updateContent(value); return; } source = new UpdateSource(value); MAP.put(key, source); engine.addSharedFunction(source); } public void remove(String key) { UpdateSource source = MAP.get(key); if (source != null) { source.updateContent(new StringBuilder(0)); } } }
测试:
public class AppConfig extends JFinalConfig { //... 方法代码此处省略书写 @Override public void onStart() { //写在onStart方便测试 //以及系统启动时加载数据库的模板。我们是在Controller管理数据库时 调用更新方法的 EngineSharedFunctionKit.web().put("1", "#define layout() aaa #end"); Template tpl = EngineSharedFunctionKit.getWebEngine() .getTemplateByString("---#@layout?()---"); System.out.println(tpl.renderToString()); //更新 EngineSharedFunctionKit.web().put("1", "#define layout() bbb #end"); System.out.println(tpl.renderToString()); //删除 EngineSharedFunctionKit.web().remove("1"); System.out.println(tpl.renderToString()); } }
启动结果:
好了,有参考价值就点个赞呗~ 有特殊业务自行改造吧~