在Docker环境中,Spring ResourceUtils或DefaultResourceLoader无法获取类path资源

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

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

要么

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

他们两个在本地环境中正常运行,但是当我打包应用程序并在Docker镜像中运行它时,它会抛出exception。 我如何获得资源? 谢谢!

如果我理解正确,则尝试从文件系统加载文件。 文件位置使用环境variables传入。

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

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

另外:你可以添加一个Spring Boot应用程序属性而不是一个环境variables。 然后在您的容器中设置一个与您的属性相同的名称的环境variables。 Spring Boot应该默认selectvariables。

不用让容器知道使用-e参数的variables,也可以使用env_file 。 这使您可以将所有环境variables放入一个文件中,并将它们推送到容器中。

结合Spring Boot应用程序属性,可以使用单个文件中定义的环境variables覆盖所有应用程序属性。 我认为这是在容器中configurationBoot应用程序的一个很好的一致的方法。