简体   繁体   English

使用Docker env中的Spring ResourceUtils或DefaultResourceLoader无法获取classpath资源

[英]Can't get classpath resource with spring ResourceUtils or DefaultResourceLoader in Docker env

I am developing a spring-boot web app, and i need to get some classpath resources, so i use the method below: 我正在开发一个spring-boot网络应用程序,我需要获得一些类路径资源,所以我使用下面的方法:

@Autowired
private Enviroment env;



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

or 要么

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

Both of them run normally in the local enviroment, but when i pack the app and run it in a Docker image, it throw an exception. 它们都在本地环境中正常运行,但是当我打包应用程序并在Docker镜像中运行它时,它会抛出异常。 How can i get the resource? 我怎样才能获得资源? Thanks! 谢谢!

If I understand correctly, you try to load a file from the filesystem. 如果我理解正确,您尝试从文件系统加载文件。 The file location is passed in using an environment variable. 使用环境变量传入文件位置。

If that is correct, you can add the file you need in your Dockerfile using ADD myresource.file /myresource.file . 如果这是正确的,您可以使用ADD myresource.file /myresource.fileDockerfileADD myresource.file /myresource.file This puts myresource.file into the root of your container. 这会将myresource.file放入容器的根目录中。

Now, if you run your container, you can pass your environment variable common.cert-location using docker run -e common.cert-location=/myresource.file . 现在,如果运行容器,可以使用docker run -e common.cert-location=/myresource.file传递环境变量common.cert-location

One addition: you can add a Spring Boot application property instead of an environment variable. 另外一个:您可以添加Spring Boot应用程序属性而不是环境变量。 Then set an environment variable with the same name like your property in your container. 然后设置一个环境变量,其名称与容器中的属性相同。 Spring Boot should pick up the variable by default. Spring Boot应该默认选择变量。

Instead of letting the container know the variable using the -e parameter, you can also use env_file . 您也可以使用env_file ,而不是让容器使用-e参数知道变量。 This allows you to put all your environment variables into a single file and push them into the container. 这允许您将所有环境变量放入单个文件中并将它们推入容器中。

In combination with Spring Boot application properties, this allows you to override all application properties with environment variables defined in a single file. 结合Spring Boot应用程序属性,这允许您使用单个文件中定义的环境变量覆盖所有应用程序属性。 I think that is a nice, consistent way of configuring Boot apps inside containers. 我认为这是在容器内配置Boot应用程序的一种很好的,一致的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM