我的Spring Boot项目中有几个带有SQL查询的文件.这些查询按路径定位
spring-boot-sql-in-files/src/main/resources/sql/query.sql
Run Code Online (Sandbox Code Playgroud)
当我运行我的应用程序时,我执行这些查询加载到静态变量.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用IDE运行它时工作正常,但是当我运行name.jar文件时它不起作用,我得到以下错误:
java.io.FileNotFoundException: File 'src/main/resources/sql/query.sql' does not exist
Run Code Online (Sandbox Code Playgroud)
我该如何修复这条路?
src/main/resources喜欢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();
}
}
Run Code Online (Sandbox Code Playgroud)
这样的事情应该可以解决问题.
| 归档时间: |
|
| 查看次数: |
1393 次 |
| 最近记录: |