【问题标题】:Can't get classpath resource with spring ResourceUtils or DefaultResourceLoader in Docker env无法在 Docker env 中使用 spring ResourceUtils 或 DefaultResourceLoader 获取类路径资源
【发布时间】:2017-05-11 04:01:36
【问题描述】:

我正在开发一个spring-boot web app,我需要获取一些classpath资源,所以我使用下面的方法:

@Autowired
private Enviroment env;



 String fileLocation = ResourceUtils.getFile(env.getProperty("common.cert-location")).getAbsolutePath();

String fileLocation = new DefaultResourceLoader().getResource("filename").getFile().getPath();

它们都在本地环境中正常运行,但是当我打包应用程序并在 Docker 映像中运行它时,它会抛出异常。我怎样才能获得资源?谢谢!

【问题讨论】:

  • 将卷附加到容器,但给出相对于 docker 容器的路径。
  • @SJayesh 谢谢,我是 docker 的菜鸟,我用 'docker-maven-plugin' 运行我的应用程序,我的 Dockerfile 中的卷只是 '/tmp',那么相对的是什么'src/main/resources' 的路径应该是?
  • 我从未使用过 'docker-maven-plugin',但你能分享一下异常堆栈吗?
  • @SJayesh 谢谢,我已经通过使用“BaseController.class.getClassLoader().getResourceAsStream()”解决了这个问题

标签: java spring docker spring-boot classpath


【解决方案1】:

如果我理解正确,您尝试从文件系统加载文件。文件位置是使用环境变量传入的。

如果正确,您可以使用ADD myresource.file /myresource.fileDockerfile 中添加您需要的文件。这会将myresource.file 放入容器的根目录中。

现在,如果您运行容器,则可以使用 docker run -e common.cert-location=/myresource.file 传递您的环境变量 common.cert-location

一个补充:您可以添加 Spring Boot 应用程序属性而不是环境变量。然后设置一个与容器中的属性同名的环境变量。 Spring Boot 应该默认选择这个变量。

除了使用-e 参数让容器知道变量之外,您还可以使用env_file。这允许您将所有环境变量放入一个文件中并将它们推送到容器中。

结合 Spring Boot 应用程序属性,这允许您使用在单个文件中定义的环境变量覆盖所有应用程序属性。我认为这是在容器内配置 Boot 应用程序的一种很好且一致的方式。

【讨论】:

  • 我已经通过使用“BaseController.class.getClassLoader().getResourceAsStream()‌​”解决了这个问题,谢谢,但我不知道为什么 Spring ResourceUtils 无法获取资源,我'将阅读源代码找出原因,再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-08
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
相关资源
最近更新 更多