我的Spring Boot项目中有很少的SQL查询文件。这些查询按路径
定位spring-boot-sql-in-files/src/main/resources/sql/query.sql
当我运行我的应用程序时,我执行将这些查询加载到静态变量。
private static final String PATH_PREFIX = "src/main/resources/sql/";
public static String loadQueryFromFile(@NonNull String fileName) {
try {
return FileUtils.readFileToString(new File(PATH_PREFIX + fileName), Charset.defaultCharset());
} catch (Exception e) {
log.error("Error occurred during loading sql file to string, file=" + fileName, e);
throw new QueryNotLoadedException();
}
}
当我使用IDE运行它时工作正常但是当我运行name.jar
文件时它不起作用,我收到以下错误:
java.io.FileNotFoundException: File 'src/main/resources/sql/query.sql' does not exist
如何修复此路径?
答案 0 :(得分:7)
src/main/resources
这样的{p> src/main/java
成为了类路径的根,因此无效。它不仅适用于sql
,也不适用于打包为jar
时的文件。而是使用Spring Resource
抽象加载文件,使用StreamUtils
将其加载到String
。
public static String loadQueryFromFile(@NonNull String fileName) {
try {
Resource resource = new ClassPathResource("sql/" + fileName);
return StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
} catch (Exception e) {
log.error("Error occurred during loading sql file to string, file=" + fileName, e);
throw new QueryNotLoadedException();
}
}
这样的事情应该可以解决问题。