SpringBoot velocity 模板配置绝对路径的资源路径

    xiaoxiao2022-07-07  186

    velocity 配置模板路径是class path 下面相对的。

    如果我们再boot 生产环境下,对应模板路径在class path 下那么将一并打包到jar 中。这样的情况我们就没有办法随时修改模板文件。这样对于一个产品维护是相当不方便的。那么就需要配置到一个jar 包的绝对路径中。这样我们可以随时修改,并且可以随时生效。

    1.配置boot application.properties

    spring.velocity.charset=UTF-8 spring.velocity.content-type=text/html spring.velocity.properties.input.encoding=UTF-8 spring.velocity.properties.output.encoding=UTF-8 spring.velocity.properties.file.resource.loader.class=com.yoke.common.FileResourceLoader spring.velocity.expose-request-attributes=true spring.velocity.expose-session-attributes=true spring.velocity.toolbox-config-location=toolbox.xml spring.velocity.enabled=true spring.velocity.resource-loader-path=/boot/vm/ spring.velocity.suffix=.vm

    其中 spring.velocity.properties.file.resource.loader.class 属性是修改我们模板加载资源类(在这个类中我们需要进行自定义)

    spring.velocity.resource-loader-path 是配置我们资源所在的绝对路径

    com.yoke.common.FileResourceLoader 类的代码如下:

    package com.yoke.common; /** * Created by jiangzeyin on 2017/1/5. */ import com.yoke.system.SystemBean; import com.yoke.system.log.SystemLog; import org.apache.commons.collections.ExtendedProperties; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.runtime.resource.Resource; import org.apache.velocity.runtime.resource.loader.ResourceLoader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; /** * @author jiangzeyin * @create 2017 01 05 18:30 */ public class FileResourceLoader extends ResourceLoader { Map<String, Long> fileLastModified = new HashMap<>(); @Override public void init(ExtendedProperties configuration) { } @Override public InputStream getResourceStream(String source) throws ResourceNotFoundException { File file = null; try { file = getResourceFile(source); return new FileInputStream(file); } catch (FileNotFoundException e) { SystemLog.LOG().info("FileNotFoundException:" + source + " " + file.getPath()); return this.getClass().getResourceAsStream(source); } finally { if (file != null) fileLastModified.put(source, file.lastModified()); } } @Override public boolean isSourceModified(Resource resource) { long lastModified = resource.getLastModified(); File file = getResourceFile(resource.getName()); return lastModified != file.lastModified(); } @Override public long getLastModified(Resource resource) { return fileLastModified.get(resource.getName()); } private File getResourceFile(String name) { return new File(String.format("%s/%s", SystemBean.getInstance().VelocityPath, name)); } }

    这个类主要是去加载对应资源,velocity 默认是对资源有缓存的,也就是加载一次资源后,第二次直接读缓存。这样即使我们改了模板内容实际显示还是没有变更前的。这里我们使用map 对模板资源文件的最后一次修改时间进行一次缓存。每一次读取资源是先判断最后一次修改时间是否变更。

    其中60行 SystemBean.getInstance().VelocityPath 是对 application.properties 中的spring.velocity.resource-loader-path 属性值进行读取。

    最新回复(0)