【问题标题】:Spring Boot FileNotFoundException when getting resource in Docker container在 Docker 容器中获取资源时出现 Spring Boot FileNotFoundException
【发布时间】:2021-09-22 12:31:53
【问题描述】:

我正在将 Docker 用于 Spring 启动应用程序。我想将 JSON 文件用于我的 Google 令牌身份验证。虽然我在我的机器上本地运行它,但一切正常。但是当我在 docker 环境中运行它时,出现以下异常:

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

这个file.json 位于/src/main/resources/file.json 获取这个文件我使用下面的代码:

@Throws(FileNotFoundException::class, IOException::class)
fun getAccessToken(): AccessToken? {

    val resource =  ClassPathResource("file.json")
    val inputStream: InputStream = resource.inputStream

    val credentials: GoogleCredentials = GoogleCredentials.fromStream(
        inputStream
    ).createScoped(
        "https://www.googleapis.com/auth/...",
        "https://www.googleapis.com/auth/..."
    )


    return credentials.accessToken
}

我也尝试使用以下方法。

@Value("classpath:/file.json")
lateinit var resource: Resource

@Throws(FileNotFoundException::class, IOException::class)
fun getAccessToken(): AccessToken? {
   val inputStream: InputStream = resource.inputStream

   val credentials: GoogleCredentials = GoogleCredentials.fromStream(
            inputStream
        ).createScoped(
            "https://www.googleapis.com/auth/...",
            "https://www.googleapis.com/auth/..."
        )

两种方法都抛出相同的异常。任何评论都将不胜感激。

【问题讨论】:

    标签: spring-boot docker kotlin


    【解决方案1】:

    下面的代码对我有用:

    val credentials: GoogleCredentials = GoogleCredentials.fromStream(
                this.javaClass.getResourceAsStream("/file.json")
            ).createScoped(
                "https://www.googleapis.com/auth/...",
                "https://www.googleapis.com/auth/..."
            )
    

    由于某种原因,如果我将 inputStream 作为变量传递,它就不起作用。如果有人知道为什么我会很感激。

    【讨论】:

      猜你喜欢
      • 2018-10-31
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2015-02-03
      相关资源
      最近更新 更多