springboot打成jar包加载静态文件异常

springboot引用js方法,本地运行时没问题的,打成jar包就会找不到文件,报异常(具体原因参考:ClassPathResource获取classpath下文件失败),异常:

class path resource [static] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app.jar!/BOOT-INF/classes!/static

原因是我使用的加载文件的方法加载不到jar包里面的文件,修改了加载方式。

原始代码

public class EncryptUtils {
    public static Map encrypt(String json) {
        try {
            Path dir = ResourceUtils.getFile("classpath:static/js").toPath();
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            if (engine instanceof Invocable) {
                Invocable invocable = (Invocable) engine;
                engine.eval(new FileReader(dir.resolve("jsencrypt.min.js").toAbsolutePath().toString()));
                engine.eval(new FileReader(dir.resolve("common.js").toAbsolutePath().toString()));
                Object common = engine.get("common");
                Map encryptedParams = (ScriptObjectMirror) invocable.invokeMethod(common, "postParamMake", json);
                return new HashMap<>(encryptedParams);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        throw new RuntimeException("初始化js异常");
    }
}

修改后的代码

import jdk.nashorn.api.scripting.ScriptObjectMirror;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class EncryptUtils {

    public static Map encrypt(String json) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            if (engine instanceof Invocable) {
                Invocable invocable = (Invocable) engine;
                engine.eval(new InputStreamReader(Objects.requireNonNull(EncryptUtils.class.getResourceAsStream("/static/jsencrypt.min.js"))));
                engine.eval(new InputStreamReader(Objects.requireNonNull(EncryptUtils.class.getResourceAsStream("/static/common.js"))));
                Object common = engine.get("common");
                Map encryptedParams = (ScriptObjectMirror) invocable.invokeMethod(common, "postParamMake", json);
                return new HashMap<>(encryptedParams);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        throw new RuntimeException("初始化js异常");
    }
}

以前使用的是 ResourceUtils.getFile来获得路径,现在直接用类.class.getResourceAsStream("/static/common.js")获得文件路径

你可能感兴趣的:(springboot,spring,boot,jar,java)